<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:creativeCommons="http://backend.userland.com/creativeCommonsRssModule" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0">

<channel>
	<title>Goyelloblog</title>
	
	<link>http://blog.goyello.com</link>
	<description>Sharing our daily IT experience</description>
	<lastBuildDate>Fri, 17 May 2013 09:53:12 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.5.1</generator>
		<atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/goyello/uokR" /><feedburner:info uri="goyello/uokr" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><creativeCommons:license>http://creativecommons.org/licenses/by-sa/3.0/</creativeCommons:license><image><link>http://creativecommons.org/licenses/by-sa/3.0/</link><url>http://creativecommons.org/images/public/somerights20.gif</url><title>Some Rights Reserved</title></image><feedburner:emailServiceId>goyello/uokR</feedburner:emailServiceId><feedburner:feedburnerHostname>http://feedburner.google.com</feedburner:feedburnerHostname><item>
		<title>Express names in code: Bad vs Clean</title>
		<link>http://feedproxy.google.com/~r/goyello/uokR/~3/80FXHxjXYrA/</link>
		<comments>http://blog.goyello.com/2013/05/17/express-names-in-code-bad-vs-clean/#comments</comments>
		<pubDate>Fri, 17 May 2013 08:02:04 +0000</pubDate>
		<dc:creator>Mateusz Roszczak</dc:creator>
				<category><![CDATA[Best practices]]></category>
		<category><![CDATA[Software development]]></category>
		<category><![CDATA[Clean code]]></category>
		<category><![CDATA[coding notation]]></category>
		<category><![CDATA[comments]]></category>
		<category><![CDATA[defining concepts]]></category>
		<category><![CDATA[meaningful names]]></category>
		<category><![CDATA[naming]]></category>

		<guid isPermaLink="false">http://blog.goyello.com/?p=4673</guid>
		<description><![CDATA[Beginner programmers always spend a lot of time on learning a programming language, code syntax, technology and tools. They think, if  they master the craft of technologies, they will become good programmers. However, object programming is not about mastering the tools, it is about creating a solution to a problem in a particular domain and to do it in cooperation with [...]<div class="crp_related"><h3>Related Posts:</h3><ul><li><a href="http://blog.goyello.com/2011/10/12/fast-face-detection-by-apple-in-ios/"     class="crp_title">Fast face detection by Apple in iOS</a></li><li><a href="http://blog.goyello.com/2011/11/23/entity-framework-invalid-operation/"     class="crp_title">Entity Framework Invalid Operation Exception – a bug or&hellip;</a></li><li><a href="http://blog.goyello.com/2013/01/21/top-9-principles-clean-code/"     class="crp_title">Top 9 qualities of clean code</a></li><li><a href="http://blog.goyello.com/2013/01/30/6-more-things-c-developers-should-not-do/"     class="crp_title">6 more things C# developers should (not) do</a></li><li><a href="http://blog.goyello.com/2013/01/07/8-most-common-mistakes-c-developers-make/"     class="crp_title">8 Most common mistakes C# developers make</a></li></ul></div>]]></description>
				<content:encoded><![CDATA[<p></p><p style="text-align: left">Beginner programmers always spend a lot of time on learning a programming language, code syntax, technology and tools. They think, if  they master the craft of technologies, they will become good programmers. However, object programming is not about mastering the tools, it is about creating a solution to a problem in a particular domain and to do it in cooperation with other programmers. Therefore, it is very important to express your thoughts in code precisely and in a result to be understood by other people.<span id="more-4673"></span></p>
<p style="text-align: left">Let&#8217;s start with a great quote by the Clean Code guru, Robert C. Martin:</p>

<blockquote><em>&#8220;The proper use of comments is to compensate for our failure to express our self in code&#8221;</em></blockquote>
<p style="text-align: right"><span style="font-size: small">[„Clean Code: A Handbook of Agile Software Craftsmanship” Robert C. Martin]</span></p>
<p style="text-align: left">This phrase simply means that<strong> if there is a need to comment your code, it is most probable that your code is bad</strong>. Also, it might indicate a failure when you cannot express all your thoughts about a problem or an algorithm within code without comments. And finally, that means you expressed a part of a concept in comment not in the commented code. <strong>Good code should be understandable to everyone without reading any comments</strong>. Good coding style is about storing all necessary information to understand the problem in code.</p>
<p style="text-align: left">In programming theory, there is a concept of &#8220;self-describing source code&#8221;. It is a common descriptor for source code that follows certain loosely defined conventions for naming and structure. The main objective for self-describing is to make source code easier to read and understand. Therefore, it is easier to maintain or extend existing code.</p>
<p style="text-align: left"><strong>Within the scope of this article I would like to present some examples of &#8220;bad code&#8221; compared with &#8220;clean code&#8221;.</strong></p>

<h2>Names have to reveal your intentions</h2>
<p style="text-align: left">Thinking about names is always a problem when writing code. Some programmers are trying to simplify, shorten or encode names in they-only-know way. Let&#8217;s have a look at a few examples:</p>
<strong><span style="color: #ff0000">BAD CODE:</span></strong>

<pre class="brush: csharp; title: ; notranslate">
int d;
// elapsed time in days
int ds;
int dsm;
int faid;
</pre>
<p style="text-align: left">Name &#8220;d&#8221; could mean anything. The author used comment to reveal his intentions, instead of including it in code. Name &#8220;faid&#8221; could be mistaken for identity (ID).</p>
<strong><span style="color: #339966">CLEAN CODE:</span></strong>

<pre class="brush: csharp; title: ; notranslate">
int elapsedTimeInDays;
int daysSinceCreation;
int daysSinceModification;
int fileAgeInDays;
</pre>
<h2>Avoid Disinformation</h2>
<p style="text-align: left">No information at all is better than misleading information. Sometimes programmers try to &#8220;hide&#8221; some important information, however they tend also to create confusing parts of code sometimes.</p>
<strong><span style="color: #ff0000">BAD CODE:</span></strong>

<pre class="brush: csharp; title: ; notranslate">
Customer[] customerList;
Table theTable;
</pre>
<p style="text-align: left">Variable &#8220;customerList&#8221; is not actually a list. It is a normal array (or just a collection of customers). In the second case, &#8220;theTable&#8221; is an object with a type &#8220;Table&#8221; (which you can easily check when using IDE), and the word &#8220;the&#8221; is just an unnecessary noise.</p>
<strong><span style="color: #339966">CLEAN CODE:</span></strong>

<pre class="brush: csharp; title: ; notranslate">
Customer[] customers;
Table customers;
</pre>
<h2>Good names length</h2>
<p style="text-align: left">In modern programming languages, long variable names are not a problem. You can create names almost without any limitations. Nevertheless the problem is that this could introduce a naming chaos in code.</p>
<strong><span style="color: #ff0000">BAD CODE:</span></strong>

<pre class="brush: csharp; title: ; notranslate">
var theCustomersListWithAllCustomersIncludedWithoutFilter;
var list;
</pre>
<p style="text-align: left">A good name contains as many words as are needed to express a concept. But nothing more. Any unnecessary words make the name longer and harder to understand. Short names are good only when they describe the whole concept in the current context (it is better to say &#8220;customersInOrder&#8221; than &#8220;list&#8221; in a context of making an order).</p>
<strong><span style="color: #339966">CLEAN CODE:</span></strong>

<pre class="brush: csharp; title: ; notranslate">
var allCustomers;
var customersInOrder;
</pre>
<h2>Always code in one notation, let notation help you understand the code</h2>
<p style="text-align: left">Any programming technology (language) has its own &#8220;style&#8221;, called notation. A programmer should create code that matches this notation, because other programmers probably know it and use it. Let&#8217;s have a look at a bad example of code without proper notation. The code below does not fit any &#8220;standard&#8221; well-known notation (like PascalCase, camelCase, Hungarian Notation). Moreover there is a meaningless name for bool (&#8220;change&#8221;). This is a verb (describes action), but the bool value in this case describes a state, so it is better to use an adjective-like form there.</p>
<strong><span style="color: #ff0000">BAD CODE:</span></strong>

<pre class="brush: csharp; title: ; notranslate">
const int maxcount = 1
bool change = true
public interface Repository
private string NAME
public class personaddress
void getallorders()
</pre>
<p style="text-align: left"> When you look at a part of code, you should know straight away what kind of element in object programming it is, just because of the notation.</p>
<p style="text-align: left">For example: you see &#8220;_name&#8221; and you already know that it is a private variable in the current class. You have to always use notation, without any exception.</p>
<strong><span style="color: #339966">CLEAN CODE:</span></strong>

<pre class="brush: csharp; title: ; notranslate">
const int MAXCOUNT = 1
bool isChanged = true
public interface IRepository
private string _name
public class PersonAddress
void GetAllOrders()
</pre>
<h2>Use one word per one concept. Don&#8217;t mix multiple concepts per one word</h2>
<p style="text-align: left">Defining concepts is always a problem. In software development process a lot of time is spend on analysis of a domain and proper naming of all elements. Hence, programmers also have difficulties with concepts.</p>
<strong><span style="color: #ff0000">BAD CODE:</span></strong>

<pre class="brush: csharp; title: ; notranslate">
//1.
void LoadSingleData()
void FetchDataFiltered()
Void GetAllData()
//2.
void SetDataToView();
void SetObjectValue(int value)
</pre>
<p style="text-align: left">First case:</p>
<p style="text-align: left">The author of the code tried to express a concept &#8220;get the data&#8221;, using multiple words &#8220;load&#8221;, &#8220;fetch&#8221;, &#8220;get&#8221;. Only one word per concept should be used in code (in a particular domain).</p>
<p style="text-align: left">Second case:</p>
<p style="text-align: left">A word &#8220;set&#8221; is used for 2 concepts: the first is &#8220;data loading to view&#8221;, and the second is &#8220;setting a value of object&#8221;. These concepts are not the same, so you should use different words for each one.</p>
<strong><span style="color: #339966">CLEAN CODE:</span></strong>

<pre class="brush: csharp; title: ; notranslate">
//1.
void GetSingleData()
void GetDataFiltered()
Void GetAllData()
//2.
void LoadDataToView();
void SetObjectValue(int value)
</pre>
<h2>Use meaningful names in domain context</h2>
<p style="text-align: left">All code that programmers write is connected to some domain logic. To make code more understandable to anyone involved in solving a problem, it is better to use meaningful names in a domain context.</p>
<strong><span style="color: #ff0000">BAD CODE:</span></strong>

<pre class="brush: csharp; title: ; notranslate">
public class EntitiesRelation
{
Entity o1;
Entity o2;
}
</pre>
<p style="text-align: left">When you are coding domain-specific solution, you should always use domain-specific names. In the future somebody else (not only a programmer, maybe a tester) will use your code and will be able to easily understand it in a domain context (with business logic knowledge). You should think first about the domain problem, later about how the solution is going to be implemented.</p>
<strong><span style="color: #339966">CLEAN CODE:</span></strong>

<pre class="brush: csharp; title: ; notranslate">
public class ProductWithCategory
{
Entity product;
Entity category;
}
</pre>
<h2>Use meaningful names in their self context</h2>
<p style="text-align: left">Apart from the element name in code, there is always some context that the name is used within. The context is very important to understand a name, because it has additional information. Let&#8217;s have a look at a typical &#8220;address&#8221; context:</p>
<strong><span style="color: #ff0000">BAD CODE:</span></strong>

<pre class="brush: csharp; title: ; notranslate">
string addressCity;
string addressHomeNumber;
string addressPostCode;
</pre>
<p style="text-align: left">In almost all domains, a phrase &#8220;Post Code&#8221; is a part of address and it is obvious that post code cannot exists alone (unless you are developing a post code only application). So, it is unnecessary to add &#8220;address&#8221; as a part of the name. Moreover, all the information that is connected with a variable is contained in: a variable name, a class that includes this variable and a namespace that includes the class.</p>
<p style="text-align: left">In object-oriented programming the best way is to design a class that represents an entity &#8220;Address&#8221;.</p>
<strong><span style="color: #339966">CLEAN CODE:</span></strong>

<pre class="brush: csharp; title: ; notranslate">
class Address
{
string city;
string homeNumber;
string postCode;
}
</pre>
<h2>Summary</h2>
<p style="text-align: left">To sum up, as a programmer you should:</p>

<ul>
	<li><span style="line-height: 13px">Always try to express a concept when naming any element;</span></li>
	<li>Think about the length of names, they should contain only information necessary to understand intentions;</li>
	<li>Notation helps to understand the code, so use it;</li>
	<li>Do not mix names for concepts;</li>
	<li>Let the names be meaningful in domain context and their self context.</li>
</ul>
<p style="text-align: left"><strong>Feel free to share your thoughts about this issue. If you know any other problems with naming or expressing thoughts in code that developers have, please let me know in comments below <img src='http://i1.wp.com/blog.goyello.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' data-recalc-dims="1" /> </strong></p><div class="crp_related"><h3>Related Posts:</h3><ul><li><a href="http://blog.goyello.com/2011/10/12/fast-face-detection-by-apple-in-ios/"     class="crp_title">Fast face detection by Apple in iOS</a></li><li><a href="http://blog.goyello.com/2011/11/23/entity-framework-invalid-operation/"     class="crp_title">Entity Framework Invalid Operation Exception – a bug or&hellip;</a></li><li><a href="http://blog.goyello.com/2013/01/21/top-9-principles-clean-code/"     class="crp_title">Top 9 qualities of clean code</a></li><li><a href="http://blog.goyello.com/2013/01/30/6-more-things-c-developers-should-not-do/"     class="crp_title">6 more things C# developers should (not) do</a></li><li><a href="http://blog.goyello.com/2013/01/07/8-most-common-mistakes-c-developers-make/"     class="crp_title">8 Most common mistakes C# developers make</a></li></ul></div><img src="http://feeds.feedburner.com/~r/goyello/uokR/~4/80FXHxjXYrA" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.goyello.com/2013/05/17/express-names-in-code-bad-vs-clean/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		<feedburner:origLink>http://blog.goyello.com/2013/05/17/express-names-in-code-bad-vs-clean/</feedburner:origLink></item>
		<item>
		<title>Better your code with Dependency Injection</title>
		<link>http://feedproxy.google.com/~r/goyello/uokR/~3/fQ563yLONAs/</link>
		<comments>http://blog.goyello.com/2013/03/26/better-your-code-with-dependency-injection/#comments</comments>
		<pubDate>Tue, 26 Mar 2013 07:05:37 +0000</pubDate>
		<dc:creator>Paweł Ogrodowczyk</dc:creator>
				<category><![CDATA[Agile software development]]></category>
		<category><![CDATA[Best practices]]></category>
		<category><![CDATA[Software development]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[Agile]]></category>
		<category><![CDATA[Dependency injection]]></category>
		<category><![CDATA[Inversion of control]]></category>

		<guid isPermaLink="false">http://blog.goyello.com/?p=4537</guid>
		<description><![CDATA[Dependency Injection &#8211; everybody&#8217;s doing it! It helps you write flexible, loosely coupled, reusable, testable and maintainable code. But fancy keywords aside, are you sure you know how to use it to reap all the benefits? Let&#8217;s have a look at a couple of tips on how you can use DI to help you write [...]<div class="crp_related"><h3>Related Posts:</h3><ul><li><a href="http://blog.goyello.com/2010/07/29/quick-start-with-ehcache-annotations-for-spring/"     class="crp_title">Quick start with Ehcache Annotations for Spring</a></li><li><a href="http://blog.goyello.com/2011/12/16/enhancements-spring-mvc31/"     class="crp_title">Top 5 enhancements of Spring MVC 3.1</a></li><li><a href="http://blog.goyello.com/2011/10/06/three-pillars-of-unit-tests/"     class="crp_title">Three pillars of Unit Tests</a></li><li><a href="http://blog.goyello.com/2011/06/08/jee6-cdi-and-conversation-scope/"     class="crp_title">JEE6 &#8211; CDI and Conversation Scope</a></li><li><a href="http://blog.goyello.com/2011/05/17/java-ee-6-productivity-joy/"     class="crp_title">Java EE 6 leads to productivity with joy</a></li></ul></div>]]></description>
				<content:encoded><![CDATA[<p><a class="post_image_link" href="http://blog.goyello.com/2013/03/26/better-your-code-with-dependency-injection/" title="Permanent link to Better your code with Dependency Injection"><img class="post_image alignright" src="http://i0.wp.com/blog.goyello.com/wp-content/uploads/2013/03/1.2.png?resize=200%2C200" alt="Post image for Better your code with Dependency Injection" data-recalc-dims="1" /></a>
</p><p>Dependency Injection &#8211; everybody&#8217;s doing it! It helps you write flexible, loosely coupled, reusable, testable and maintainable code. But fancy keywords aside, are you sure you know how to use it to reap all the benefits? Let&#8217;s have a look at a couple of tips on how you can use DI to help you write high quality code.</p>
<span id="more-4537"></span>

<h2>Always default to Constructor Injection</h2>
<p>DI comes in many flavors, including:</p>
<ul>
	<li>Constructor Injection,</li>
	<li>Property Injection (aka Setter Injection),</li>
	<li>Interface Injection.</li>
</ul>
<p>All of them are tasty, but <a href="http://www.martinfowler.com/articles/injection.html#ConstructorInjectionWithPicocontainer" target="_blank">Constructor Injection</a> is by far the most delicious. Why? Because it makes your class&#8217;s required dependencies explicit and ensures that they&#8217;re always available to your service. It&#8217;s also really easy to implement and as a bonus it can make your code more testable.</p>
<p>Let&#8217;s have a look at a code sample:</p>
<pre class="brush: csharp; title: ; notranslate">
public class Service : IService
{
    private readonly IDependency dependency;

    public Service(IDependency dependency)
    {
        if (dependency == null)
        {
            throw new ArgumentNullException(&quot;dependency&quot;);
        }

        this.dependency = dependency;
    }

    //Service implementation...
}
</pre>
<p>As you can see all of the dependencies of the <code>Service</code> class are explicitly stated in the class&#8217;s constructor and can be easily injected by our IoC container. Furthermore, having all of the dependencies in the constructor guarantees their availability to the service &#8211; there is no way to create an instance of <code>Service</code> without supplying something implementing <code>IDependency</code>. The null guards in the constructor&#8217;s code are an additional measure to ensure that the dependencies of the <code>Service</code> class are always satisfied.</p>
<p>Constructor Injection has another advantage &#8211; it improves testability. In our unit tests we can now simply create a <a href="http://en.wikipedia.org/wiki/Mock_object" target="_blank">mock object</a> for <code>IDependency</code>, construct an instance of the <code>Service</code> class and test it without worrying about what the actual implementation of <code>IDependency</code> does.</p>
<h2>Remember your three R&#8217;s</h2>
<p>The three R&#8217;s are:</p>
<ul>
 	<li>Register,</li>
 	<li>Resolve,</li>
 	<li>Release.</li>
</ul>
<p>Also known as the <a href="http://docs.castleproject.org/Windsor.Three-Calls-Pattern.ashx" target="_blank">Three Calls Pattern</a>, the mnemonic describes the sequence of mandatory steps that accompany the usage of an IoC container. Here&#8217;s the kicker: each of those steps should be performed only once in the entire application. Impossible? Most frameworks actually enable you to do that! Let&#8217;s examine the three R&#8217;s rule based on the example of an ASP.NET MVC application which uses Castle Windsor as an IoC container.</p>
<p><strong>Register</strong> is the first step in the sequence. This is the phase in which you create an instance of the IoC container and register your components with it. Registration should be performed in the application&#8217;s entry point. In the case of our MVC application the ideal place for this is the <code>Application_Start</code> method in the Global.asax file.</p>
<pre class="brush: csharp; title: ; notranslate">
protected void Application_Start()
{
    var container = new WindsorContainer();
    //Castle Windsor uses Installers for component registrations
    container.Install(new MyComponentsInstaller());
}
</pre>
<p>The next step, <strong>Resolve</strong>, is the place where you construct your object graph. This should be done in your application&#8217;s <a href="http://blog.ploeh.dk/2011/07/28/CompositionRoot/" target="_blank">Composition Root</a>. A good candidate for a Composition Root in an MVC application is the place where our controllers are created &#8211; a controller factory. Our controller factory class should inherit from <code>DefaultControllerFactory</code> and override the <code>GetControllerInstance</code> method.</p>
<pre class="brush: csharp; title: ; notranslate">
protected override IController GetControllerInstance(
    RequestContext requestContext, Type controllerType)
{
    return (IController)this.container.Resolve(controllerType);
}
</pre>
<p>How did the container get there? It was passed as a parameter the controller factory&#8217;s constructor.</p>
<p><strong>Release</strong> is the third and final step and coincidentally the one which is most frequently forgotten. In this phase, components that are no longer needed should be decommissioned by the container. In an MVC application this can be done in the <code>ReleaseController</code> method of our, already implemented, custom controller factory.</p>
<pre class="brush: csharp; title: ; notranslate">
public override void ReleaseController(IController controller)
{
    this.container.Release(controller);
}
</pre>
<p>Let&#8217;s sum up the whole example. Register? Check! Resolve? Check! Release? Check! Each invoked only once? Check! Having a single instance of an IoC container in the application and only three places where it&#8217;s used sure sounds like maintainability heaven, doesn&#8217;t it?</p>
<h2>Don&#8217;t use the IoC container as a Service Locator</h2>
<p>The infamous <a href="http://martinfowler.com/articles/injection.html#UsingAServiceLocator" target="_blank">Service Locator</a> is widely considered as an <a href="http://blog.ploeh.dk/2010/02/03/ServiceLocatorisanAnti-Pattern/" target="_blank">anti-pattern</a>. That goes double for trying to use an IoC container as one. Why? Because it makes you lose most of the benefits of DI and more importantly it goes against the inversion of control paradigm.</p>

<p>An IoC container is used as a Service Locator when the code contains many calls like this:</p>
<pre class="brush: csharp; title: ; notranslate">
public class Service
{
    //somewhere in a method, constructor or field initializer
    IDependency dependency = ServiceLocator.Resolve&lt;IDependency&gt;();
}
</pre>
<p>In the code sample above <code>ServiceLocator</code> denotes some kind of wrapper, static or not, on the IoC container. That&#8217;s bad due to several reasons. First of all, it introduces a hard dependency on <code>ServiceLocator</code>. Now, everywhere we use the <code>Service</code> class we have to drag the locator along with it.</p>
<p>Secondly, the dependency is implicit and even if we make it explicit (for example by making <code>ServiceLocator</code>, or even its abstraction, a constructor parameter), the dependencies the Service Locator provides will remain implicit.</p>
<p>Thirdly, how are we going to test our service? It looks like we have to use <code>ServiceLocator</code> in our tests. This hurts our testability.</p>
<p>My suggestion is: save yourself the trouble, switch to Constructor Injection, follow the three R&#8217;s rule and make your container transparent to the application you&#8217;re writing.</p>
<h2>Use convention-based registration to your advantage</h2>
<p>DI containers usually support three forms of component registration:</p>
<ul>
	<li>XML-based,</li>
	<li>Code-based,</li>
	<li>Convention-based.</li>
</ul>
<p>The first two options enable you to explicitly register components one by one. One of them uses XML files and the the other uses code. But the real power lies within the third form, which allows you to establish rules used for locating your application&#8217;s components.</p>
<p>Let&#8217;s have a look at a sample showing how we can register components using Castle Windsor&#8217;s convention-based registration API:</p>
<pre class="brush: csharp; title: ; notranslate">
public void Install(IWindsorContainer container, IConfigurationStore store)
{
    container.Register(
        Classes.FromAssemblyContaining&lt;IService&gt;()
            .Where(type =&gt; type.Name.EndsWith(&quot;Service&quot;))
            .WithServiceDefaultInterfaces()
            .LifestyleTransient());
}
</pre>
<p>The code establishes a convention that can be summed up as &#8220;Register all types which names end with &#8216;Service&#8217; and which are defined in the same assembly as <code>IService</code>. Use the default interface and a transient lifestyle for the types&#8221;. I won&#8217;t explain the Windsor-specific jargon but this simple example should give you an idea of how powerful this API is.</p>
<p>What are the advantages of such an approach? Well, the obvious one is that you don&#8217;t have to repeatedly write registration code for each new type you introduce, you only need to make sure to follow conventions. This makes the registration code more compact and <a href="http://en.wikipedia.org/wiki/Don%27t_repeat_yourself" target="_blank">DRY</a>!</p>
<p>Furthermore, you get the benefits of <a href="http://en.wikipedia.org/wiki/Convention_over_configuration" target="_blank">Convention over Configuration</a>, namely: code consistency, reduced complexity and increased developer productivity.</p>
<p>Additionally, some advanced convention code can even give you the ability to interchange components during runtime. How cool is that?</p>

<p><strong>Dependency Injection is a really powerful mechanism which can greatly improve code quality in more than one way. Has DI helped you achieve that goal? Do you have any other tips on using IoC containers? Make sure to leave a comment.</strong></p><div class="crp_related"><h3>Related Posts:</h3><ul><li><a href="http://blog.goyello.com/2010/07/29/quick-start-with-ehcache-annotations-for-spring/"     class="crp_title">Quick start with Ehcache Annotations for Spring</a></li><li><a href="http://blog.goyello.com/2011/12/16/enhancements-spring-mvc31/"     class="crp_title">Top 5 enhancements of Spring MVC 3.1</a></li><li><a href="http://blog.goyello.com/2011/10/06/three-pillars-of-unit-tests/"     class="crp_title">Three pillars of Unit Tests</a></li><li><a href="http://blog.goyello.com/2011/06/08/jee6-cdi-and-conversation-scope/"     class="crp_title">JEE6 &#8211; CDI and Conversation Scope</a></li><li><a href="http://blog.goyello.com/2011/05/17/java-ee-6-productivity-joy/"     class="crp_title">Java EE 6 leads to productivity with joy</a></li></ul></div><img src="http://feeds.feedburner.com/~r/goyello/uokR/~4/fQ563yLONAs" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.goyello.com/2013/03/26/better-your-code-with-dependency-injection/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		<feedburner:origLink>http://blog.goyello.com/2013/03/26/better-your-code-with-dependency-injection/</feedburner:origLink></item>
		<item>
		<title>6 more things C# developers should (not) do</title>
		<link>http://feedproxy.google.com/~r/goyello/uokR/~3/fuqLCowiYzU/</link>
		<comments>http://blog.goyello.com/2013/01/30/6-more-things-c-developers-should-not-do/#comments</comments>
		<pubDate>Wed, 30 Jan 2013 05:57:04 +0000</pubDate>
		<dc:creator>Pawel Bejger</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Microsoft]]></category>
		<category><![CDATA[Software development]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[HashSet]]></category>
		<category><![CDATA[OrderBy]]></category>
		<category><![CDATA[pitfalls]]></category>
		<category><![CDATA[programming mistakes]]></category>
		<category><![CDATA[ref and out keywords]]></category>
		<category><![CDATA[SortedSet]]></category>
		<category><![CDATA[string methods]]></category>

		<guid isPermaLink="false">http://blog.goyello.com/?p=4476</guid>
		<description><![CDATA[For all wondering what are the things a C# developer should and should not do. As the continuation of my previous post 8 Most common mistakes C# developers make I decided to write another article about the things C# developers should always be aware of. 1. Try to avoid using the “ref” and “out” keywords. [...]<div class="crp_related"><h3>Related Posts:</h3><ul><li><a href="http://blog.goyello.com/2013/01/07/8-most-common-mistakes-c-developers-make/"     class="crp_title">8 Most common mistakes C# developers make</a></li><li><a href="http://blog.goyello.com/2013/05/17/express-names-in-code-bad-vs-clean/"     class="crp_title">Express names in code: Bad vs Clean</a></li><li><a href="http://blog.goyello.com/2012/10/29/remote-asp-net-model-validation/"     class="crp_title">Remote ASP.NET Model Validation with generic version of&hellip;</a></li><li><a href="http://blog.goyello.com/2011/11/23/entity-framework-invalid-operation/"     class="crp_title">Entity Framework Invalid Operation Exception – a bug or&hellip;</a></li><li><a href="http://blog.goyello.com/2013/01/21/top-9-principles-clean-code/"     class="crp_title">Top 9 qualities of clean code</a></li></ul></div>]]></description>
				<content:encoded><![CDATA[<p><a class="post_image_link" href="http://blog.goyello.com/2013/01/30/6-more-things-c-developers-should-not-do/" title="Permanent link to 6 more things C# developers should (not) do"><img class="post_image alignright" src="http://i0.wp.com/blog.goyello.com/wp-content/uploads/2013/01/sheldon_cooper.jpg?resize=320%2C214" alt="What C# developers should not do" data-recalc-dims="1" /></a>
</p>For all wondering what are the things a C# developer should and should not do. As the continuation of my previous post <a title="8 Most Common Mistakes C# Developers Make" href="http://blog.goyello.com/2013/01/07/8-most-common-mistakes-c-developers-make/" target="_blank">8 Most common mistakes C# developers make</a> I decided to write another article about the things C# developers should always be aware of.

<span id="more-4476"></span>
<h2>1. Try to avoid using the “ref” and “out” keywords.</h2>
There is rarely a situation that you really have to use &#8220;ref&#8221; or &#8220;out&#8221; keywords. It should be avoided as much as possible, because when you use them it means that your method probably tries to do too much (and therefore breaks the <a title="Single Responsibility Principle" href="http://blog.goyello.com/2013/01/21/top-9-principles-clean-code/">Single Responsibility Principle</a>). It can also make your method less readable.

To accomplish the goal of not using ref/out keywords it is usually enough to create a class that will represent multiple return values and then return an instance of this class as a result of the method.

There are obviously situations when the usage of ref/out cannot be avoided like when using TryParse method, but these should be treated as exceptions to the rule.
<h2>2. Do not use OrderBy before Where</h2>
The above statement might sound very obvious but anyway some developers tend to forget about this.

Let’s take a look at the following code:

<pre class="brush: csharp; title: ; notranslate">
var allCitiesInPoland =
    allCitiesInTheWorld.OrderBy(x =&gt; x.Name)
                       .Where(x =&gt; x.Country == Country.Poland);
</pre>

In this hypothetical scenario firstly the collection of all cities in the world (according to some statistics: 2,469,501) will be sorted and then only these from Poland (897) will be returned. The result will be appropriate, the only problem is that it will be simply inefficient.

Using the following code:

<pre class="brush: csharp; title: ; notranslate">
var allCitiesInPoland =
    allCitiesInTheWorld.Where(x =&gt; x.Country == Country.Poland)
                       .OrderBy(x =&gt; x.Name);
</pre>

First of all we will choose only the cities from Poland and then order this significantly smaller collection alphabetically by name.
<h2>3. Always use Properties instead of public variables</h2>
When using getters and setters you can restrict the user directly from accessing the member variables. Secondly, you can explicitly restrict setting the values. Thanks to this you make your data protected from accidental changes. What is more, when using properties,&nbsp; it is much easier to validate your data.
<h2>4. Take advantage of string.IsNullOrEmpty() and string.IsNullOrWhiteSpace()</h2>
Instead of:

<pre class="brush: csharp; title: ; notranslate">
if (name != null &amp;&amp; name != string.Empty)
{
    [...]
}
</pre>

It’s better to use:

<pre class="brush: csharp; title: ; notranslate">
if (string.IsNullOrEmpty(name))
{
    [...]
}
</pre>

Sometimes we want to make sure that a string is not only not empty and not null, but also does not comprise of whitespaces. In such situation we could of course use the following code:

<pre class="brush: csharp; title: ; notranslate">
if (string.IsNullOrEmpty(name.Trim()))
{
    [...]
}
</pre>

But why not using something that is already provided by the .NET framework (in version 4.0 and higher):

<pre class="brush: csharp; title: ; notranslate">
if (string.IsNullOrWhiteSpace(name))
{
    [...]
}
</pre>

The example above can be treated as a more general principle. You should simply always try to find out whether something that you implemented is not already existing as a ready method in the framework that you use. Make sure that you went through all the methods in such .Net classes as e.g. String or IO.Path. This might potentially save you some time that you could have spent on reinventing the wheel.
<h2>5. Understand the difference between First() and Single()</h2>
Always remember that First() returns the very first item of the sequence, if no item exists it throws <b>InvalidOperationException, whereas Single() </b>Returns the&nbsp;<b>only</b>&nbsp;item in the sequence, if no item exists it throws&nbsp;<b>InvalidOperationException,</b>and if more than one item exists, it also throws&nbsp;<b>InvalidOperationException</b>.
<h2>6. Do not blindly use List</h2>
There are some cases when the usage of List is simply not recommended from performance point of view. You should be aware of the existence of e.g. HashSet or SortedSet which can <b>considerably</b> improve the performance, especially in case of large sets of items.

To make you aware of how big the difference in performance between these two is, let’s consider the following piece of code:

<pre class="brush: csharp; title: ; notranslate">
    class Program
    {
        static void Main(string[] args)
        {
            const int COUNT = 100000;
            HashSet&lt;int&gt; hashSetOfInts = new HashSet&lt;int&gt;();
            Stopwatch stopWatch = new Stopwatch();
            for (int i = 0; i &lt; COUNT; i++)
            {
                hashSetOfInts.Add(i);
            }

            stopWatch.Start();
            for (int i = 0; i &lt; COUNT; i++)
            {
                hashSetOfInts.Contains(i);
            }
            stopWatch.Stop();

            Console.WriteLine(stopWatch.Elapsed);

            stopWatch.Reset(); 
            List&lt;int&gt; listOfInts = new List&lt;int&gt;();
            for (int i = 0; i &lt; COUNT; i++)
            {
                listOfInts.Add(i);
            }

            stopWatch.Start();
            for (int i = 0; i &lt; COUNT; i++)
            {
                listOfInts.Contains(i);
            }
            stopWatch.Stop();

            Console.WriteLine(stopWatch.Elapsed);
            Console.Read();
        }
    }
</pre>


After executing it you will see the difference:
<br />
100000 &#8216;Contains&#8217; operations using HashSet: <b>0.002 sec</b><br />
100000 &#8216;Contains&#8217; operations using List: <b>28.74 sec</b><br />
<br />
<p>Of course HashSets or SortedSets are not golden means for every possible scenario.
<b>HashSet</b> should be used in case when you care about the performance (especially if you know that you will operate on a large set of items) but do not care about the order.
<b>SortedSet</b> is a bit slower than HashSet but will give you a sorted collection and is much faster than List.</p>
<p>Use <b>List</b> when you want to iterate through the collection. Iterating through all the items in a List it is generally much faster than through a set (unless you use inside such methods as Contains).</p>
<p><b>If you know any other thing that C# developers should or should not do feel free to share it with us and leave a comment below!
</b></p>

<p><i>P.S. What you should be aware of is that the guidelines presented in this (and in the previous post) will not suddenly make you a great C# programmer. What makes someone a good developer is the everyday compliance with the basic principles of creating high quality code which I described in details in the post <a title="Top 9 Principles of Clean Code" href="http://blog.goyello.com/2013/01/21/top-9-principles-clean-code/" target="_blank">Top 9 qualities of clean code</a>.</i></p><div class="crp_related"><h3>Related Posts:</h3><ul><li><a href="http://blog.goyello.com/2013/01/07/8-most-common-mistakes-c-developers-make/"     class="crp_title">8 Most common mistakes C# developers make</a></li><li><a href="http://blog.goyello.com/2013/05/17/express-names-in-code-bad-vs-clean/"     class="crp_title">Express names in code: Bad vs Clean</a></li><li><a href="http://blog.goyello.com/2012/10/29/remote-asp-net-model-validation/"     class="crp_title">Remote ASP.NET Model Validation with generic version of&hellip;</a></li><li><a href="http://blog.goyello.com/2011/11/23/entity-framework-invalid-operation/"     class="crp_title">Entity Framework Invalid Operation Exception – a bug or&hellip;</a></li><li><a href="http://blog.goyello.com/2013/01/21/top-9-principles-clean-code/"     class="crp_title">Top 9 qualities of clean code</a></li></ul></div><img src="http://feeds.feedburner.com/~r/goyello/uokR/~4/fuqLCowiYzU" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.goyello.com/2013/01/30/6-more-things-c-developers-should-not-do/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		<feedburner:origLink>http://blog.goyello.com/2013/01/30/6-more-things-c-developers-should-not-do/</feedburner:origLink></item>
		<item>
		<title>Top 9 qualities of clean code</title>
		<link>http://feedproxy.google.com/~r/goyello/uokR/~3/lfRj3A9cFPU/</link>
		<comments>http://blog.goyello.com/2013/01/21/top-9-principles-clean-code/#comments</comments>
		<pubDate>Mon, 21 Jan 2013 08:34:23 +0000</pubDate>
		<dc:creator>Pawel Bejger</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Best practices]]></category>
		<category><![CDATA[Software development]]></category>
		<category><![CDATA[Clean code]]></category>
		<category><![CDATA[DRY]]></category>
		<category><![CDATA[Good developer]]></category>
		<category><![CDATA[KISS]]></category>
		<category><![CDATA[Single Responsibility Principle]]></category>

		<guid isPermaLink="false">http://blog.goyello.com/?p=4352</guid>
		<description><![CDATA[How often do you express your disbelief when browsing through someone&#8217;s code saying out loud “Omg, that’s real spaghetti code&#8230;” ? Probably quite often. And how sure are you that no one thought the same when working with your code? In other words, how sure are you that your code is clean? The truth is [...]<div class="crp_related"><h3>Related Posts:</h3><ul><li><a href="http://blog.goyello.com/2013/01/30/6-more-things-c-developers-should-not-do/"     class="crp_title">6 more things C# developers should (not) do</a></li><li><a href="http://blog.goyello.com/2011/10/06/three-pillars-of-unit-tests/"     class="crp_title">Three pillars of Unit Tests</a></li><li><a href="http://blog.goyello.com/2013/05/17/express-names-in-code-bad-vs-clean/"     class="crp_title">Express names in code: Bad vs Clean</a></li><li><a href="http://blog.goyello.com/2011/08/29/what-does-tdd-mean/"     class="crp_title">What does TDD mean?</a></li><li><a href="http://blog.goyello.com/2011/12/20/software-development-balancefunctionality-technology/"     class="crp_title">How to find the right balance in between functionality and&hellip;</a></li></ul></div>]]></description>
				<content:encoded><![CDATA[<p><a class="post_image_link" href="http://blog.goyello.com/2013/01/21/top-9-principles-clean-code/" title="Permanent link to Top 9 qualities of clean code"><img class="post_image alignright" src="http://i2.wp.com/blog.goyello.com/wp-content/uploads/2013/01/clean_code_72_color1.png?resize=200%2C200" alt="Clean Code" data-recalc-dims="1" /></a>
</p><p>How often do you express your disbelief when browsing through someone&#8217;s code saying out loud “Omg, that’s real spaghetti code&#8230;” ? Probably quite often. And how sure are you that no one thought the same when working with your code? In other words, how sure are you that your code is clean? The truth is that you can only be sure if you fully know what clean code means.</p>
<p><span id="more-4352"></span></p>
<p>It is hard to create a precise definition of clean code and probably there are as many definitions as developers. However, some principles that lead to a basic level of clean code apply. I have gathered the 9 most relevant ones and described them in short below.</p>
<h2>1. Bad code does too much &#8211; Clean code is focused</h2>
<p>Each class, method or any other entity should remain undisturbed. It should conform to <a title="Single Responsibility Principle" href="http://en.wikipedia.org/wiki/Single_responsibility_principle" target="_blank">SRP</a> (Single Responsibility Principle). Shortly speaking, we can say that SRP (according to some well-known definitions) is about making sure that if you can think of the reason for changing a class you should not be able to come up with more than one.</p>
<p>Though, I wouldn&#8217;t limit this definition only to the concept of classes. In his latest article <a title="Ralf Westphal" href="http://www.developerfusion.com/profile/ralfw/">Ralf Westphal</a> presents a broader definition of Single Responsibility Principle. According to his definition:</p>
<blockquote>
<p>A functional unit on a given level of abstraction should only be responsible for a single aspect of a system’s requirements. An aspect of requirements is a trait or property of requirements, which can change independently of other aspects.</p>
</blockquote>
<p>If you would like to read more about the quoted thesis I advise you to dig into <a title="Single Responsibility Principle" href="http://www.developerfusion.com/article/137636/taking-the-single-responsibility-principle-seriously/" target="_blank">his article</a>.</p>
<h2>2.  The language you wrote your code with should look like it was made for the problem</h2>
<blockquote>
<p>It is not the language that makes a program look simple, but the programmer who makes the language appear simple.</p>
</blockquote>
<p style="text-align: right;">(quote from Robert C. Martin)</p>
<p>This means, for instance, that you shouldn&#8217;t use workarounds which make code and language usually look awkward. If you claim that something can only be done by means of a workaround, it usually means that you haven&#8217;t spent enough time on trying to find a good, clean solution.</p>
<h2>3. It should not be redundant</h2>
<p>It should comply with the <a title="DRY" href="http://en.wikipedia.org/wiki/Don't_repeat_yourself">DRY</a> rule (Don’t Repeat Yourself). When the DRY principle has successfully been applied, the modification of any single element of a system doesn&#8217;t require a change in any other logically unrelated elements.</p>
<h2>4. Reading your code should be pleasant</h2>
<p>When  browsing through the code you should feel like reading Harry Potter (yeah I know that&#8217;s a slight exaggeration <img src='http://i1.wp.com/blog.goyello.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' data-recalc-dims="1" /> ). You should feel that it was made to be read by any developer easily without hours spent on digging into it.</p>
<p>To achieve this you should try to comply with the <a title="KISS" href="http://en.wikipedia.org/wiki/KISS_principle">KISS</a> principle (Keep It Simple, Stupid!) and <a title="YAGNI" href="http://en.wikipedia.org/wiki/You_ain't_gonna_need_it" target="_blank">YAGNI</a> principle (You Ain&#8217;t Gonna Need It). The KISS principle states that most systems work best if they are kept simple rather than made complex.</p>
<p>Therefore, simplicity should be a key goal in design, and unnecessary complexity should be avoided. YAGNI is a practice encouraging to purely focus on the simplest things that make your software work.</p>
<h2>5. Can be easily extended by any other developer</h2>
<p>You don&#8217;t write code for yourself , or worse -  for a compiler. You write code for other developers. Don&#8217;t be selfish – think about the others. Don&#8217;t torture other developers by producing a hardly maintainable and extendable code. Besides, in some months time you could be that &#8220;other developer&#8221; yourself.</p>
<h2>6. It should have minimal dependencies</h2>
<p>The more dependencies it has, the harder it is to maintain and change it in the future. You can always help yourself in achieving the goal of having minimal dependencies by using e.g. <a title="NDEPEND" href="http://www.ndepend.com/" target="_blank">NDEPEND</a> for checking potential incorrectness in the dependencies of your code.</p>
<h2>7. Smaller is better</h2>
<p>Code should be minimal. Both classes and methods should be short, preferably just a few lines of code. It should be well divided (also within one class). The better you divide your code the easier it becomes to read it. This principle might positively influence point 4 &#8211; it will make it easier for other developers to understand your code.</p>
<h2>8. It should have unit and acceptance tests</h2>
<p>How can we know that our code complies with the requirements if we don&#8217;t write tests? How can we maintain and extend it without the fear that it will stop working? Code without tests is simply not clean. If you would like to get to know more about the pillars of unit testing I advise you to read a very nice article <a title="Three Pillars of unit tests" href="http://blog.goyello.com/2011/10/06/three-pillars-of-unit-tests/">Three Pillars of Unit Tests</a> written by one of my colleagues.</p>
<h2>9. It should be expressive</h2>
<p>Expressiveness of the code means that it has meaningful names. These names should express their intention. They should not mislead you. They should be distinctive. Expressiveness makes code document itself making the need for documentation less important. If you want to read more about the subject of self-documenting code I recommend you to go through <a title="Self-Documenting Code" href="http://c2.com/cgi/wiki?SelfDocumentingCode">this article</a>.</p>
<h2>So what is in fact the definition of clean code?</h2>
<p>All in all there is one final quality that summarizes all the above:</p>
<blockquote>
<p style="text-align: left;">Clean code is a code that is written by someone who cares</p>
</blockquote>
<p style="text-align: right;"> quote from Michael Feathers</p>
<p>It is written by someone who has treated it as an art and paid attention to all details.</p>
<p><strong>The subject of clean code is in fact very complex and goes far beyond the knowledge presented in this post. Therefore if you find any other characteristics that you think make code cleaner do not hesitate and share them with us!</strong></p>
<div class="crp_related"><h3>Related Posts:</h3><ul><li><a href="http://blog.goyello.com/2013/01/30/6-more-things-c-developers-should-not-do/"     class="crp_title">6 more things C# developers should (not) do</a></li><li><a href="http://blog.goyello.com/2011/10/06/three-pillars-of-unit-tests/"     class="crp_title">Three pillars of Unit Tests</a></li><li><a href="http://blog.goyello.com/2013/05/17/express-names-in-code-bad-vs-clean/"     class="crp_title">Express names in code: Bad vs Clean</a></li><li><a href="http://blog.goyello.com/2011/08/29/what-does-tdd-mean/"     class="crp_title">What does TDD mean?</a></li><li><a href="http://blog.goyello.com/2011/12/20/software-development-balancefunctionality-technology/"     class="crp_title">How to find the right balance in between functionality and&hellip;</a></li></ul></div><img src="http://feeds.feedburner.com/~r/goyello/uokR/~4/lfRj3A9cFPU" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.goyello.com/2013/01/21/top-9-principles-clean-code/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		<feedburner:origLink>http://blog.goyello.com/2013/01/21/top-9-principles-clean-code/</feedburner:origLink></item>
		<item>
		<title>8 Most common mistakes C# developers make</title>
		<link>http://feedproxy.google.com/~r/goyello/uokR/~3/8kQbxv5IyJE/</link>
		<comments>http://blog.goyello.com/2013/01/07/8-most-common-mistakes-c-developers-make/#comments</comments>
		<pubDate>Mon, 07 Jan 2013 08:53:51 +0000</pubDate>
		<dc:creator>Pawel Bejger</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Microsoft]]></category>
		<category><![CDATA[Software development]]></category>
		<category><![CDATA[AutoMapper]]></category>
		<category><![CDATA[DAL optimization]]></category>
		<category><![CDATA[disposing objects]]></category>
		<category><![CDATA[LINQ]]></category>
		<category><![CDATA[programming mistakes]]></category>
		<category><![CDATA[rethrowing exceptions]]></category>

		<guid isPermaLink="false">http://blog.goyello.com/?p=3831</guid>
		<description><![CDATA[While working with (young) C# programmers I&#8217;ve noticed that some mistakes are being repeated by almost every one of them. These are mostly the mistakes, which once you point them, are quite easy to remember. However, if a developer is not aware of them, they can cause many problems with the efficiency and quality of [...]<div class="crp_related"><h3>Related Posts:</h3><ul><li><a href="http://blog.goyello.com/2013/01/30/6-more-things-c-developers-should-not-do/"     class="crp_title">6 more things C# developers should (not) do</a></li><li><a href="http://blog.goyello.com/2012/10/29/remote-asp-net-model-validation/"     class="crp_title">Remote ASP.NET Model Validation with generic version of&hellip;</a></li><li><a href="http://blog.goyello.com/2011/11/23/entity-framework-invalid-operation/"     class="crp_title">Entity Framework Invalid Operation Exception – a bug or&hellip;</a></li><li><a href="http://blog.goyello.com/2013/05/17/express-names-in-code-bad-vs-clean/"     class="crp_title">Express names in code: Bad vs Clean</a></li><li><a href="http://blog.goyello.com/2011/09/30/mvc3-forms-authentication-using-strongly-typed-user-roles/"     class="crp_title">MVC3 Forms Authentication using strongly typed User Roles</a></li></ul></div>]]></description>
				<content:encoded><![CDATA[<p><a class="post_image_link" href="http://blog.goyello.com/2013/01/07/8-most-common-mistakes-c-developers-make/" title="Permanent link to 8 Most common mistakes C# developers make"><img class="post_image alignright" src="http://i2.wp.com/blog.goyello.com/wp-content/uploads/2012/03/programming_mistakes-e1331471647964.jpg?resize=230%2C230" alt="Most Common Programming Mistakes" data-recalc-dims="1" /></a>
</p><p>While working with (young) C# programmers I&#8217;ve noticed that some mistakes are being repeated by almost every one of them. These are mostly the mistakes, which once you point them, are quite easy to remember. However, if a developer is not aware of them, they can cause many problems with the efficiency and quality of the developed software. Therefore, I decided to gather the 8 most common mistakes made.</p>
<span id="more-3831"></span>
<h2>1. String concatenation instead of StringBuilder</h2>
<p>String concatenation works in such a way that every time when you add something to a string, a new address in the memory is being allocated. The previous string is copied to a new location with the newly added part. This is inefficient. On the other hand we have StringBuilder which keeps the same position in the memory without performing the copy operation. Thanks to the strings’ appending by means of StringBuilder the process is much more efficient, especially in case of hundreds of append operations.</p>
<pre class="brush: csharp; title: ; notranslate">
//INCORRECT
List values = new List(){&quot;This &quot;,&quot;is &quot;,&quot;Sparta &quot;,&quot;!&quot;};
string outputValue = string.Empty;
foreach (var value in values)
{
   outputValue += value;
}
</pre>
<p>&nbsp;</p>
<pre class="brush: csharp; title: ; notranslate">
//CORRECT
StringBuilder outputValueBuilder = new StringBuilder();
foreach (var value in values)
{
   outputValueBuilder.Append(value);
}
</pre>
<h2>2. LINQ &#8211; &#8216;Where&#8217; with &#8216;First&#8217; instead of FirstOrDefault</h2>
<p>A lot of programmers find a certain set of elements by means of &#8216;Where&#8217; and then return the first occurrence. This is inappropriate, because the &#8216;First&#8217; method can be also applied with the &#8216;Where&#8217; condition. What&#8217;s more, it shouldn&#8217;t be taken for granted that the value will always be found. If &#8220;First&#8221; is used when no value is found, an exception will be thrown. Thus, it&#8217;s better to use FirstOrDefault instead. When using FirstOrDefault, if no value has been found, the default value for this type will be returned and no exception will be thrown.</p>
<pre class="brush: csharp; title: ; notranslate">
//INCORRECT
List numbers = new List(){1,4,5,9,11,15,20,21,25,34,55};
return numbers.Where(x =&gt; Fibonacci.IsInFibonacciSequence(x)).First();
</pre>
<p>&nbsp;</p>
<pre class="brush: csharp; title: ; notranslate">
//PARTLY CORRECT
return numbers.First(x =&gt; Fibonacci.IsInFibonacciSequence(x));
</pre>
<p>&nbsp;</p>
<pre class="brush: csharp; title: ; notranslate">
//CORRECT
return numbers.FirstOrDefault(x =&gt; Fibonacci.IsInFibonacciSequence(x));
</pre>
<h2>3. Casting by means of &#8216;(T)&#8217; instead of &#8216;as (T)&#8217; when possibly not castable</h2>
<p>It&#8217;s common that software developers use simple &#8216;(T)&#8217; casting, instead of &#8216;as (T)&#8217;. And usually it doesn&#8217;t have any negative influence because casted objects are always castable. Yet, if there is even a very slight probability that an object can be under some circumstances not castable, „as (T)” casting should be used. See <a title="Prefix-casting versus as-casting in C#" href="http://www.codingware.com/2011/02/difference-between-c-cast-syntax-and-as.html" target="_blank">Difference Between C# Cast Syntax and the AS Operators</a> for more details.</p>
<pre class="brush: csharp; title: ; notranslate">
//INCORRECT
var woman = (Woman)person;
</pre>
<p>&nbsp;</p>
<pre class="brush: csharp; title: ; notranslate">
//CORRECT
var woman = person as Woman;
</pre>
<h2>4. Not using mapping for rewriting properties</h2>
<p>There are a lot of ready and very powerful C# mappers (e.g. <a title="AutoMapper" href="http://automapper.org/" target="_blank">AutoMapper</a>). If a few lines of code are simply connected with rewriting properties, it&#8217;s definitely a place for a mapper. Even if some properties aren&#8217;t directly copied but some additional logic is performed, using a mapper is&nbsp;still&nbsp;a good choice (mappers enable defining the rules of rewriting properties to a big extend).</p>
<h2>5. Incorrect exceptions re-throwing</h2>
<p>C# programmers usually forget that when they throw an exception using „throw ex” they loose the stack trace. It is then considerably harder to debug an application and to achieve appropriate log messages. When simply using „throw” no data is lost and the whole exception together with the stack trace can be easily retrieved.</p>
<pre class="brush: csharp; title: ; notranslate">
//INCORRECT
try
{
   //some code that can throw exception [...]
}
catch (Exception ex)
{
   //some exception logic [...]
   throw ex;
}
</pre>
<p>&nbsp;</p>
<pre class="brush: csharp; title: ; notranslate">
//CORRECT
try
{
   //some code that can throw exception [...]
}
catch (Exception ex)
{
   //some exception logic [...]
   throw;
}
</pre>
<h2>6. Not using &#8216;using&#8217; for objects disposal</h2>
<p>Many C# software developers don&#8217;t even know that &#8216;using&#8217; keyword is not only used as a directive for adding namespaces, but also for disposing objects. If you know that a certain object should be disposed after performing some operations, always use the &#8216;using&#8217; statement to make sure that the object will actually be disposed.</p>
<pre class="brush: csharp; title: ; notranslate">
//the below code:
using(SomeDisposableClass someDisposableObject = new SomeDisposableClass())
{
   someDisposableObject.DoTheJob();
}
//does the same as:
SomeDisposableClass someDisposableObject = new SomeDisposableClass();
try
{
   someDisposableObject.DoTheJob();
}
finally
{
   someDisposableObject.Dispose();
}
</pre>
<h2>7. Using &#8216;foreach&#8217; instead of &#8216;for&#8217; for anything else than collections</h2>
<p>Remember that if you want to iterate through anything that is not a collection (so through e.g. an array), using the &#8216;for&#8217; loop is much more efficient than using the &#8216;foreach&#8217; loop. See <a title="Foreach vs For Loop" href="http://www.codeproject.com/Articles/6759/FOREACH-Vs-FOR-C" target="_blank">Foreach vs For Performance</a> for more details.</p>
<h2>8. Retrieving or saving data to DB in more than 1 call</h2>
<p>This is a very common mistake, especially among junior developers and especially when using ORMs like Entity Framework or NHibernate. Every DB call consumes some amount of time and therefore it&#8217;s crucial to decrease the amount of DB calls as much as possible. There are many ways to do so:</p>
<ul>
<li>Using fetching (Eager Loading)</li>
<li>Enclosing DB operations in transactions</li>
<li>In case of a really complex logic, just moving it to the DB by building a stored procedure</li>
</ul>
<p><strong>It goes without saying that there are hundreds of other types of mistakes made by C# programmers. If you know any interesting ones or you want to share your opinion about the subject, feel free to leave a comment below!&nbsp;</strong></p>
<p>
If you would like to read more about common mistakes of C# developers read <a href="http://blog.goyello.com/2013/01/30/6-more-things-c-developers-should-not-do/" title="6 More Things C# Developers Should Not Do" target="_blank">this post</a>.
</p><div class="crp_related"><h3>Related Posts:</h3><ul><li><a href="http://blog.goyello.com/2013/01/30/6-more-things-c-developers-should-not-do/"     class="crp_title">6 more things C# developers should (not) do</a></li><li><a href="http://blog.goyello.com/2012/10/29/remote-asp-net-model-validation/"     class="crp_title">Remote ASP.NET Model Validation with generic version of&hellip;</a></li><li><a href="http://blog.goyello.com/2011/11/23/entity-framework-invalid-operation/"     class="crp_title">Entity Framework Invalid Operation Exception – a bug or&hellip;</a></li><li><a href="http://blog.goyello.com/2013/05/17/express-names-in-code-bad-vs-clean/"     class="crp_title">Express names in code: Bad vs Clean</a></li><li><a href="http://blog.goyello.com/2011/09/30/mvc3-forms-authentication-using-strongly-typed-user-roles/"     class="crp_title">MVC3 Forms Authentication using strongly typed User Roles</a></li></ul></div><img src="http://feeds.feedburner.com/~r/goyello/uokR/~4/8kQbxv5IyJE" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://blog.goyello.com/2013/01/07/8-most-common-mistakes-c-developers-make/feed/</wfw:commentRss>
		<slash:comments>72</slash:comments>
		<feedburner:origLink>http://blog.goyello.com/2013/01/07/8-most-common-mistakes-c-developers-make/</feedburner:origLink></item>
	</channel>
</rss><!-- Dynamic page generated in 2.444 seconds. --><!-- Cached page generated by WP-Super-Cache on 2013-05-19 00:05:59 -->
