Some practices to write better C#/.NET code

February 8, 2013 § Leave a comment

I was reading an article on code project and I totally agree with this article below. There are lot of things that makes simple when code is written right

 

Just re posting in my blog

 

Some practices to write better C#/.NET code

By Monjurul Habib,

Introduction

Developers always love to fight about coding standards. But it is very vital to follow coding standards to achieve consistency throughout the project or code. All should be of the same mind that conventions are very influential. I will show some good practices that i have learned during my professional years, those are lower level but very important for all levels.

Quick Test

Let us demonstrate a FizzBuzz example. The FizzBuzz test is to write a program that goes through the numbers 1 to 100. For every multiple of 3, the program should output “Fizz” and for every multiple of 5 it should output “Buzz”. If both above conditions are met it should output “FizzBuzz”. If none of the above conditions are met, it should just output the number.

Example 1:

 Collapse | Copy Code
public void Test()
       {
           for (int i = 1; i < 101; i++)
           {
               string Output = "";
               if (i % 3 == 0) { Output = "Fizz"; }
               if (i % 5 == 0) { Output += "Buzz"; }
               if (Output == "") { Output = i.ToString(); }
               Console.WriteLine(Output);
           }
       }

What do you think ? Do we need to make the code better?
Example 2:

 Collapse | Copy Code
public void Check()
       {
           for (int i = 1; i <= 100; i++)
           {
               string output = "";
               if (i % 3 == 0) { output = "Fizz"; }
               if (i % 5 == 0) { output += "Buzz"; }
               if (output == "") { output = i.ToString(CultureInfo.InvariantCulture); }
               Console.WriteLine(output);
           }
       }

What do you think now ? Do we need to make the code even better?

Ok, let me help you to make it better. Naming thing is one of the hardest job we have as a software developer. Because we spend a lot of time naming things, there are so many things to name properties, methods, classes, files, projects etc. We should spend some energies for naming things because names can be meanings. Adding meaning to code is readability all about.

 Collapse | Copy Code
     public void DoFizzBuzz()
       {
           for (int number = 1; number <= 100; number++)
           {
               var output = GetFizzBuzzOutput(number);
               Console.WriteLine(output);
           }
       }

     private static string GetFizzBuzzOutput(int number)
       {
           string output = string.Empty;
           if (number%3 == 0)
           {
               output = "Fizz";
           }
           if (number%5 == 0)
           {
               output += "Buzz";
           }
           if (string.IsNullOrEmpty(output))
           {
               output = number.ToString(CultureInfo.InvariantCulture);
           }
           return output;
       }

What do you think now? Is it better than previous examples ? isn’t it more readable?

What is better Code?

Write code for People First, Computers Second. Readable code doesn’t take any longer to write than confusing code does, at least not in the long run. It’s easier to be sure your code works if you can easily read what you wrote. That should be a sufficient reason to write readable code. But code is also read during reviews. It’s read when you or someone else fixes an error. It’s read when the code is modified. It’s read when someone tries to use part of your code in a similar project.

“What if you just writing code for yourself? Why should you make it readable?”

Because a week or two from now you’re going to be working on another project. What will happen when any other HUMAN needs to fix an error on that project? I can guarantee you that you will also lost within your own horror code.


From my point of view a better should carried out the following characteristics:

  • Code that is easy to write , modify and extend
  • Code that is clean and talks/convey meaning
  • Code that has values and cares about quality

there are many more but above are very import.

How can you improve the Readability?

First You have to read other peoples code and figure out what is good and what is bad within that code. What makes you easy to understand and what makes you feel more complicated. Then apply those things to your own code. Finally you need sometime, some experience and you need some practice to improve the readability of your code. It is very hard but obvious to implement standards in any software company, through methods like Trainings, Peer Code Reviews, Introducing automated code review tools etc. Most popular tools are as follows:

FxCop is a tool that performs static code analysis of .NET code. It provides hundreds of rules that perform various types of analysis.

StyleCop is an open source project that analyzes C# source code to enforce a set of style and consistency rules. It can be run from inside of Visual Studio or integrated into an MSBuild project. StyleCop has also been integrated into many third-party development tools.

JetBrains ReSharper is a renowned productivity tool that makes Microsoft Visual Studio a much better IDE. Thousands of .NET developers worldwide wonder how they’ve ever lived without ReSharper’s code inspections, automated code refactoring, blazing fast navigation, and coding assistance.

What are Conventions?

You should be able to tell the difference between a property, local variable, method name, class name etc. because they use different capitalization conventions. These type of conventions has values. You will be able to get lots of guidelines and conventions over internet. So find a convention or build your own and stick with it.

The source of the following (Design Guidelines for Developing Class Libraries) was developed by the Microsoft special interest group. I just made some addons.

Capitalization Conventions

Below are some examples of our C# coding standards, naming conventions, and best practices. Use these according to your own needs.

Pascal Casing

The first letter in the identifier and the first letter of each subsequent concatenated word are capitalized. You can use Pascal case for identifiers of three or more characters.

Camel Casing

The first letter of an identifier is lowercase and the first letter of each subsequent concatenated word is capitalized.


Ref. Capitalization Rules for Identifiers

Example of some Naming Conventions Guidelines

You will find enough resources over internet. I am just highlighting some of my favorites among them

C# Coding Conventions
C# Coding Guidelines
C# Coding Standards and Best Programming Practices
C# Coding Standards and Naming Conventions

I am providing some basic level examples below but as I already mentioned, find a good convention that fits for you and stick with it.

DO use PascalCasing for class names and method names.

 Collapse | Copy Code
public class Product
{
    public void GetActiveProducts()
    {
      //...
    }
    public void CalculateProductAdditinalCost()
    {
        //...
    }
}

DO use camelCasing for method arguments and local variables.

 Collapse | Copy Code
public class ProductCategory
{
  public void Save(ProductCategory productCategory)
   {
       // ...
   }
}

DO NOT use Abbreviations

 Collapse | Copy Code
// Correct
ProductCategory productCategory;

// Avoid
ProductCategory prodCat;

DO NOT use Underscores in identifiers

 Collapse | Copy Code
// Correct
ProductCategory productCategory;

// Avoid
ProductCategory product_Category;

DO prefix interfaces with the letter I.

 Collapse | Copy Code
public interface IAddress
{

}

DO declare all member variables at the top of a class, with static variables at the very top.

 Collapse | Copy Code
public class Product
{
    public static string BrandName;

    public string Name{get; set;}
    public DateTime DateAvailable {get; set;}

    public Product()
    {
        // ...
    }
}

DO use singular names for enums. Exception: bit field enums.

 Collapse | Copy Code
public enum Direction
{
    North,
    East,
    South,
    West
}

DO NOT suffix enum names with Enum

 Collapse | Copy Code
//Avoid
public enum DirectionEnum
{
    North,
    East,
    South,
    West
}

Why we need Conventions?

Conventions offer several specific benefits. They let you take more for granted. By making one global decision rather than many local ones, you can concentrate on the more important characteristics of the code.

  • They help you transfer knowledge across projects
  • They help you learn code more quickly on a new project.
  • They emphasize relationships among related items.

Programmers on large projects sometimes go overboard with conventions. They establish so many standards and guidelines that remembering them becomes a full-time job. The computer doesn’t care whether your code is readable. It’s better at reading binary machine instructions than it is at reading high-level-language statements.
You should write readable code because it helps other people to read your code. Naming thing is one of the hardest job we have as a software developer. Because we spend a lot of time naming things, there are so many things to name properties, methods, classes, files, projects etc. We should spend some energies for naming things because names can be meanings. Adding meaning to code is readability all about.

So it will help you better sleep at night.

 

Top Rules Developer Should Follow

Try to Avoid Comments

This is topic create some interesting conversations among all level of developers. But I almost never write comments on my code. Most comments i have ever seen is trying to describe the purpose/intentions. But comments are meaningless and C# compilers ignores comments.They have no impact what the code really does.They don’t influence the generated code at all. Most of comments are meaningless noise.

 Collapse | Copy Code
//ensure that we are not exporting
 //deleted products
  if(product.IsDeleted && !product.IsExported )
    {
       ExportProducts = false;
    }

But if name the method like CancelExportForDeletedProducts() instead of comments what will happen? Method names are more affective than comments. Methods execute and they are real.But comment is ok when visual studio will take comments for creating an API documentation and those comments are different, you can use “///” for those comments so that other developers can get intelligence of your API or Library.

I am NOT telling you that avoid comment is a must for all the times. If comment is trying to describe the purpose/intentions then it is wrong. If you look at thickly commented code, you will notice that most of those comments are there because the code is bad. Please read the following books for further detail:

  • Professional Refactoring in C# & ASP.NET” by Danijel Arsenovski
  • Refactoring: Improving the Design of Existing Code” by Martin FowlerKent BeckJohn BrantWilliam Opdykedon Roberts

Avoid Unnecessary Regions in Class

Regions are a feature of VS that allow you to surround blocks of code. It could be a single or multiple methods. The region exists because it is easier to navigate around the large file. The regions are used to hide ugly code or class that have exploded in size . If a class does too many things it also violates the Single Responsibility Principle. So next time whenever you will think for adding a new region to your file take step back and ask that is it possible to separate your region into a separate class.

Keep method Short

The more lines of code in a method the harder it is to understand. Everyone recommends 20-25 lines of code is ok. But I do prefer 1-10 lines for safe. But there is no hard and fast rule for this just make sure that you are not violatingSRP.

Avoid Too Many Parameters

Declare a class instead of too many parameters. Creating a class that puts all these parameters together. This is generally a better design and valuable abstraction.

 Collapse | Copy Code
//avoid
public void Checkout(string shippingName, string shippingCity, string shippingSate, string shippingZip, string billingName, string billingCity, string billingSate, string billingZip)
       {

       }
 Collapse | Copy Code
//DO
public void Checkout(ShippingAddress shippingAddress,BillingAddress billingAddress)
        {

        }

We should introduce class instead of all parameters.

Avoid Complex Expressions

 Collapse | Copy Code
if(product.Price>500 && !product.IsDeleted && !product.IsFeatured && product.IsExported)
          {
             // do something
          }

Complex expression have some meaning behind them it is just hidden by those multiple expressions. We can Encapsulated the complex expression into that object by using a property. That code will be easier to read.

Consider Warnings as Errors


If you notice the code you will find a variable that was declared but never used. Normally if we build the project we will get a warning and we can run our project without any error. But we should remove warning as much as possible. So setup your build to treat warning as Errors like the following steps:


 

Avoid Multiple Exit Points

This rule is very easy to follow. Developer should try to maintain single exit point and entry point.

 Collapse | Copy Code
 //avoid
         if(product.Price>15)
           {
               return false;
           }
           else if(product.IsDeleted)
           {
               return false;
           }
           else if(!product.IsFeatured)
           {
               return false;
           }
           else if()
           {
               //.....
           }
           return true;
 Collapse | Copy Code
 //DO
       var isValid = true;
           if(product.Price>15)
           {
               isValid= false;
           }
           else if(product.IsDeleted)
           {
               isValid= false;
           }
           else if(!product.IsFeatured)
           {
               isValid= false;
           }
           return isValid;

You can imagine 4 exit points scattered around 20- 30 lines of code.That makes you more harder to understand and see what is happening inside the method and what will execute and when will execute.

I got too many responses, some agreeing but mostly disagreeing that it was a good  “standard” to enforce. To find out the potentiality I did some unit testing and found that for complex method that have multiple exit points usually have a set of tests for each of those paths. Once work is done, get the heck out of there isn’t always possible because sometime you need to clean up your resources as well.

 Collapse | Copy Code
if( BADFunction() == true)
 {
    // expression
    if( anotherFunction() == true )
    {
     // expression
     return true;
    }
    else
    {
         //error
    }
 }
 else
 {
    //error
 }
 return false;
 Collapse | Copy Code
  if( !GoodFunction())
 {
    // error.
    return false
 } 
     // expression
 if( !GoodFunction2())
 {
    //error.
    return false;
 }
 // more expression
 return true;

Please read Controlling Loops chapter from the book “Code Complete” by Steve McConnell for further detail clarification on Multiple Exit Points.

Assertion

An assertion is code that’s used during development—usually a routine or macro—that allows to check itself as it runs.True means everything is operating as expected. False means it has detected an unexpected error in the code.An assertion usually takes two arguments: a boolean expression that describes the assumption that’s supposed to be true and a message to display if it isn’t.

Assertions are especially useful in large, complicated and in high reliability system.

Example: If a system assumes that there will be maximum 100,000 user records, the system might contain an assertion that the number of records is less than or equal to 100,000. So assertion will be silent within that range. If it encounters more than that records,it will loudly “assert” that there is an error in the program.

Checking Loop Endpoints

A single loop usually has three cases of interest: the first case, an arbitrarily selected middle case, and the last case.If you have any special cases that are different from the first or last case, check those too. If the loop contains complex computations, get out your calculator and manually check the calculations.

Conclusion

It is obvious to implement standards in any software company according to organizational behavior, project nature and domain. So I would like to repeat “Find a convention and stick with it.” .

If you think I missed any prominent guideline,please leave that in the comments section. I’ll try to include that in the main post. Coding For Fun.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s

What’s this?

You are currently reading Some practices to write better C#/.NET code at Naik Vinay.

meta

%d bloggers like this: