How To Write Effective C# Code
Print Friendly, PDF & Email

The purpose of this blog is to allow you guys to understand and see a few of the ways in which your programs can be made better in reading and performing. Developers always love to fight about coding standards, but it is very difficult to follow coding standards to achieve consistency throughout the project or code.

In this article, we will go through some of the common coding misses and ways to address them. These proven coding practices can help with writing better, effective and maintainable code.

Why do we need to write the effective code?

It is very important to write the effective code in any enterprise software development.

Below are the points from where we can understand the importance of effective code:

  • It helps when someone tries to reuse the code.
  • It helps reviewer to understand the code easily.
  • It helps to understand better when re-visiting the code.
  • It helps when someone else fixes the bugs.
  • It helps to improve the performance.

How can we write the effective/quality code?

There are many ways to make our code effective but also these are not limited. Let’s discuss some of the important guidelines as follows:

Naming convention

Using proper naming convention, we will be able to tell the difference between a property, local variable, method name, class name etc. because they use different capitalization conventions.

Following are some examples of our C# coding standards like naming conventions and best practices. Use these as per your requirement.

Pascal Casing: For your better practice, you can use Pascal case for identifiers of three or more characters. The first letter of the identifier and the first letter of each subsequent concatenated word are capitalized.

You should use Pascal Casing for all public member, type and namespace names consisting of multiple words.

Example:

public class employee
{
    public void GetEmployeeDetails()
    {
      //...
    }
    public void CalculateSalary()
    {
        //...
    }
}

Camel Casing: Identifier name of the first letter is lowercase and the first letter of each subsequent concatenated word is capitalized.

You should use camelCasing for method arguments and local variables.

Example:

public class ItemCategory
{
  public void Save(ItemCategory itemCategory)
   {
       // ...
   }
} 

You should not use underscores in identifiers:

Example:

// Correct
ItemCategory itemCategory;
 
// Avoid
ItemCategory item_Category;

Different types of identifiers and capitalization rules are given below:

Identifier Casing Example
Namespace Pascal namespace System.Security { ... }
Type Pascal public class StreamReader { ... }
Interface Pascal public interface IEnumerable { ... }
Method Pascal public class Object {
public virtual string ToString();
}
Property Pascal public class String {
public int Length { get; }
}
Event Pascal public class Process {
public event EventHandler Exited;
}
Field Pascal public class MessageQueue {
public static readonly TimeSpan
InfiniteTimeout;
}
public struct UInt32 {
public const Min = 0;
}
Enum value Pascal public enum FileMode {
Append,
...
}
Parameter Camel public class Convert {
public static int ToInt32(string value);
}

Why we need conventions?

Several specific benefits offered by conventions. They let you take more for granted.  You can concentrate on the more important characteristics of the code by making one global decision rather than many local ones.

  • Across the projects, they help you transfer knowledge.
  • They help you learn to code more quickly on a new project.
  • They emphasize relationships among related items.

Avoid using very short abbreviations

Sometimes it doesn’t give the sense of their parent object and make the confusion if you use the very short name. Below are the examples of short and recommended names.

Example:

ItemSales ItSal; //Avoid
ItemSales ItemSales; //Recommended

Try to use singular name

Example:

public enum Color
{
Red,
Green,
Blue
}

public interface ItemSales
{

}

Try to use object initializers

When you create the object you should also initialize the value of its at the same time rather than first creating the object and then be assigning values.

Avoid using:

Employee emp = new Employe ee();
emp.EmpId = 501;
emp.EmpName = “Amul”;
emp.EmpCity = “Surat”;

Good to have:

Employee emp = new Employee() { EmpId = 501, EmpName = “Amul”, EmpCity = “Surat” };

Try to use auto-implemented properties

Unless there is some custom logic needed in getter/setter, instead of creating them in a traditional way using the private variable go for auto auto-Implemented properties.

Avoid to use:

private string empId;
public string EmpId
{
get
{
return empId;
}
set
{
empId = value;
}
}

Good to have:

public string EmpId { get; set; }

Avoid using multiple numbers of return

We should not use multiple returns from a same routine. Use a return when it enhances readability. In certain routines, once you know the answer, you want to return it to the calling routine immediately.

Avoid to use:

if(item.Price>15)
{
return false;
}
else if(item.IsDeleted)
{
return false;
}
else if(!item.IsFeatured)
{
return false;
}
else if()
{
//…..
}
return true;

Good to have:

var isValid = true;
if(item.Price>15)
{
isValid= false;
}
else if(item.IsDeleted)
{
isValid= false;
}
else if(!item.IsFeatured)
{
isValid= false;
}
return isValid;

Avoid complex expressions

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

Example:

if(product.Price>500 && !product.IsDeleted &&
!product.IsFeatured && product.IsExported)
{
// do something

}
Consider warning as error

Usually, 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.

Avoid too many parameters

Avoid to use:

public void Checkout(string shippingName, string shippingCity,
string shippingSate, string shippingZip, string billingName,
string billingCity, string billingSate, string billingZip)
{

}

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.

Avoid unnecessary regions in class

Regions are a feature of VS that allows you to surround blocks of code. Regions could be a single or multiple methods which are provided by the VS. The regions are used to hide ugly code or class that have exploded in size.

Keep method short

There is no hard and fast rule regarding method length. Mostly developers recommend 20-25 lines of code is ok. But some geeks prefer 1-10 lines for safety, this their personal preference.  It is very difficult to understand if the meth0d has more line of codes.

Keep class size small

According to Martin’s definition:”THERE SHOULD NEVER BE MORE THAN ONE REASON FOR A CLASS TO CHANGE.

Why do we need to separate these two responsibilities into individual classes? Because every responsibility has its own axis. If the requirements change, that change will be reflected in a change in responsibility amongst the classes. There will be more than one reason for it to change if a class assumes more than one responsibilities.

The above-mentioned tips which are related to the enhancement of our programs can be made better in reading and performance. These are not only the limitations, but of course, by using them you can see the major improvements in your quality code. For more technology blogs, visit https://www.loginworks.com/blogs/

  •  
  •  
  •  
  •  
  •  

LEAVE A REPLY

Please enter your comment!
Please enter your name here