Important Tips To Write Clean Code In C#

I remember those days when I started my career in programming. I struggled to write a piece of code and who cared for the coding standards at that time. As time went on, I was getting some command over programming and was able to think of particular scenarios to solve problems. From the start of my career until today, I have found a continity, and that is learning. At that stage, I was learning to manage basic things and now, I am learning to handle the problems. So, in life, learning is a never-ending process. Everyday, we learn something, whether it's from reading articles, watching videos, or by our own mistakes or success in this programming environment.

As per my experience, we should not write our code like a layman. We should follow some coding standard to write clean, reusable, readable, and maintainable code.

I don't know exactly how many people are following coding standards. Even I was not perfectly following the coding standards. However, here are some of the coding guidelines that I used to follow.
To develop reusable, reliable, readable, well-structured, and maintainable application, we must follow the coding standard. There are several coding practices in the software industry. None of them are good or bad but the main thing is that whatever approach we follow, we should make sure that everyone should follow the same standard.



Code Smell

Code Smell is a technical word used to describe the quality of code - how a programmer writes this code.

Code smell is often a word used to describe code that you don't like. In that sense, it is synonymous to ugly, dirty, unclean,repeated, etc. Even though these types of code work perfectly but are hard to handle and maintain.There are a few reasons why our code smells.
  1. Duplicated Code
  2. Methods too big
  3. Classes with too many instance variables
  4. Classes with too much code
  5. Lazy class / freeloader
Now, let's see how we can write clean code and avoid these smells in the programme. Let's continue our discussion from the basic coding standard, that is, on Naming Convention.

While we are coding, we shall focus on our naming standard. There are 2 main types of naming standards that we are using these days.
  • Pascal casing
    A word with the first letter capitalized, and the first letter of each subsequent word-part capitalized.
    Ex - CustomerName, EmployeeDetails, Salary,etc.

  • Camel casing
    A word with the first letter lowercase, and the first letter of each subsequent word-part capitalized.
    EX-customerName, employeeDetails, salary
Let's see where we will use which type of casing.

Always use class name and method name in Pascel casing.
  1. public class EmployeeDetails  
  2.   {  
  3.       .......  
  4.   
  5.   }  
 Now, this is how we declare methods inside a class.
  1. public class EmployeeDetails  
  2.  {  
  3.      public void GetEmployeeSalary()  
  4.      {  
  5.          ---------------  
  6.            
  7.      }  
  8.        
  9.   
  10.  }  
 Always use variables and parameter names in Camel casing.
  1. public class EmployeeDetails  
  2.   {  
  3.       private int totalSalary = 0;  
  4.       public void GetEmployeeSalary( int employeeId)  
  5.       {  
  6.           int amount = 30000;  
  7.   
  8.   
  9.       }  
  10.         
  11.   
  12.   }  
Always use letter "I" as prefix with name of interface. After letter I, use Pascal case.  
  1. using System;  
  2.   
  3.   
  4. namespace cleanacode  
  5. {  
  6.     interface IEmployee  
  7.     {  
  8.         void GetDetails();  
  9.     }  
  10. }  
Use meaningful variables and method names while coding. These names should be self descriptive.

For this, I have created two samples of code. Check the first piece of code. Do you think this code will work effectively for maintainance and code review purposes?
  1.  public class EmployeeDetails  
  2.     {  
  3.   
  4.         public void GetSalary(int x, int p)  
  5.         {  
  6.             int z = x + p;                                             
  7.   
  8.   
  9.         }  
  10. }  
 
When a new developer checks this code, what he will understand? Now, check the same piece of code with a well organized and good coding standard.
  1. public class EmployeeDetails  
  2.     {  
  3.   
  4.         public void GetEmployeeSalaryint salary, int bonus)  
  5.         {  
  6.             int totalSalary = salary + bonus;  
  7.   
  8.   
  9.         }  
  10.           
  11.   
  12.     }  
 
Always rename the variables with a descriptive name. Don't use unnecessary name for any variable so that it will be easy to maintain.
 
Whenever you are writting any method, always try to write the purpose of the method. Use summary or normal comments to specify the purpose of methods with the short description of parameters.

Here, in this example, we will show how to use this.

 

So, you can use summary by writing three forward slashes in VS.
  1. public class EmployeeDetails  
  2.     {  
  3.         /// <summary>  
  4.         /// To calculate total salary.  
  5.         /// </summary>  
  6.         /// <param name="salary"></param>  
  7.         /// <param name="bonus"></param>  
  8.   
  9.         public void GetEmployeeSalary( int salary, int bonus)  
  10.         {  
  11.             int totalSalary = salary + bonus;  
  12.   
  13.   
  14.         }  
  15.           
  16.   
  17.     }  
Don't use long method in the project. If by any chance you are using the long method, please use region to make it easy to understand.
  1. /// <summary>  
  2.         /// To calculate total salary.  
  3.         /// </summary>  
  4.         /// <param name="userId"></param>  
  5.         /// <param name="bonus"></param>  
  6.         /// <param name="noOfDays"></param>  
  7.         /// <param name="tax"></param>  
  8.         /// <param name="deduction"></param>  
  9.   
  10.         public void GetEmployeeSalary(string userId,int bonus,int noOfDays,float tax,float deduction)  
  11.         {  
  12.             float bsal;  
  13.             float hra;  
  14.             float da;  
  15.             float pf;  
  16.             float extra;  
  17.             float total;  
  18.  
  19.             #region BasicSalary  
  20.   
  21.             float monthlySalary = EmployeeDetails.GetSalary("UI54");  
  22.             float basicSalary = monthlySalary + bonus;  
  23.  
  24.  
  25.             #endregion  
  26.  
  27.             #region Calculate PF  
  28.             pf= 15 * basicSalary / 100;  
  29.  
  30.  
  31.             #endregion  
  32.  
  33.             #region Calculate HRA  
  34.   
  35.             hra= 20 * basicSalary / 100;  
  36.  
  37.             #endregion  
  38.  
  39.             #region Extra  
  40.   
  41.             extra = 2 * basicSalary / 100;  
  42.  
  43.             #endregion  
  44.  
  45.             #region Netsalary after deduction  
  46.   
  47.             total = basicSalary - (pf + hra + extra);  
  48.  
  49.             #endregion  
  50.   
  51.   
  52.   
  53.         }  
  54.         /// <summary>  
  55.         /// getting user salary  
  56.         /// </summary>  
  57.         /// <param name="userId"></param>  
  58.         /// <returns></returns>  
  59.         public static int GetSalary(string userId)  
  60.         {  
  61.             if (userId=="UI100")  
  62.             {  
  63.                 return 60000;  
  64.             }  
  65.             else  
  66.             {  
  67.                 return 45000;  
  68.             }  
  69.   
  70.               
  71.         }  
  72.           
Now, if we press CTRL+M+O, it will minimze the window and we will get the output like this.


So, if you want to define region, you can define your region by #.

 

Remove unnecessary namespace from your class. Writing unnecessary namespace will slow down your intelliSense capacity to load all classes, methods, etc. So, by removing these namespaces, you can increase your intelliSense performance.

In big projects, it will be very difficult to identify which referances are refered in the class. So you can remove this using the following way.

 
 
This option will remove all the unnecessary namespsces used in the class. The main benifit of removing Usings from the projects are-
  • Clean Code
  • IntelliSense runs faster as there are few things to search from the namespaces.
While working with HTML or ASP.NET, do proper formatting of your code section otherwise it will look confusing and messy.



To format your section, right click on any particular section and then select Format Section.This will display your code in a well organized manner.



So, these are some of the primary steps we need to follow for writing clean code.

Now, let's see some third party tools like (ReSharper and stylecop) and find out how we can write clean and consistant code in our project.

Before exploring ReSharper, let's check what it is.

ReSharper is a refactoring tool for Visual Studio which helps in finding compiler errors, runtime errors, redundancies, and code smells right as you type, suggesting intelligent corrections for them. It helps to follow coding standard throughout the project. For using ReSharper, we need to download the ReSharper from here



Initially, it comes with 30 days trial and this much time is enough to check this product. Now, downoload and install it as per the steps.

 
Here, you have the option to choose Visual Studio where you want to integrate this ReSharper.

 

After this, click Continue to install it completely.

 
 
After complete installation, close the Vsual Studio instance and open it again. Once you open a new instance and open any project, you will find the ReSharper option in the top right.

  
 
Now, let's check how we can improve our coding standard using ReSharper. To find all your compiler errors, runtime errors, redundancies, you have to follow this option.

 
Now finally, a window will open which shows all your coding issues.

 

So solving these issues is very easy. It provides quick-fixes for most errors and other detected code issues. Also, it helps you to improve code instantly.

If you want to check out these naming rules, just go to 

ReSharper - Options - C# and check the following things.

 

Besides these, it helps in showing architecture diagram of the whole project. To checck the architecture diagram, please do the following steps. ReSharper - Architecture - Show project dependency Diagram.



Anyhow, this offers a lot of code Refactoring techniques when you start working on it. You will know more about it. To know more about using ReSharper, please check the following link.

Similarly, we have one more most refactoring tool called StyleCop.This is a free tool. To use this, you have to download and install this StyleCop.

StyleCop provides value by enforcing a common set of style rules for C# code. StyleCop will continue to ship with a single, consistant set of rules, with minimal rule configuration allowed.

You can find the download link here
 
After downloading, please install this. Once you successfully install the StyleCop, restart the Visual Studio now. Right click on your project
and you will see the following context menu.



The StyleCop setting defines the rules you need to implement on the projects.
 
 

If you want to see any rules from here, you need to expand it. Then you will find the overview of the rule.

 
 
Now, to see all the code issue just run the StyleCop.



Now, click the output tab to show the warning.
 
 

In this way, we can use StyleCop and ReSharper for writing clean code and follow coding standard throughout the project.