Tuesday, November 9, 2021

Clean Code for C# developer

01Naming Convention 

Names should be readable, meaningful and better to use camel case notation,  avoid using bad names,  Hungarian notation and Misleading Names,

Ex: 

    //Bad Code

            int a;  // bad naming

            int iNumber; string strEmployeeName ;// Hungarian notation

            var dbData = db.entityService.GetAllEmployee(); // misleading Naming
           
            var employeesalary;  //missing camelCase notation  

            public double GetTotalAmount(decimal unitprice, int quantity)
            {
                    // some logic
            }
           
  //Good Code
            int numberOfDays  // readable meaningful name
            var employeeList = factory.employeeService.GetAllEmployee();
           
             var employeeSalary;  //use camlecase Notation  
             public double GetTotalAmount(decimal unitPrice, int quantity)
             {
                    // some logic
             }


02. Avoid nesting too deeply 

Too many if else statements can make the code hard to follow.  Do not used if else statements,  avoid else statement, Explicit is better than implicit.

ex 1: 

//Bad
public bool IsValidDay(string day)
{
    if (!string.IsNullOrEmpty(day))
    {
        day = day.ToLower();
        if (day == "friday")
        {
            return true;
        }
        else if (day == "saturday")
        {
            return true;
        }
        else if (day == "sunday")
        {
            return true;
        }
        else
        {
            return false;
        }
    }
    else
    {
        return false;
    }

}


//Good
public bool IsValidDay(string day)
{
    if (string.IsNullOrEmpty(day))
    {
        return false;
    }

    var openingDays = new[] { "friday", "saturday", "sunday" };
    return openingDays.Any(d => d == day.ToLower());
}


03. Avoid Magic String

keep string on centralized pace and used it.  

            //Bad Code
            if(userRole == "Admin"){

            }

            //Good Code
            const string ADMIN_ROLE = "Admin"
            if (userRole == ADMIN_ROLE)
            {
                // logic in here
            }

04. Don't repeat class name in variable 


//Bad code
public class Account{
    public string AccountName{get;set;}
    public string AccountCurrency {get;set;}
    public string AccountCode {get;set;}
}

//Good code
public class Account{
    public string Name{get;set;}
    public string Currency {get;set;}
    public string Code {get;set;}
}


05. Use default variable than short circuit or conditional 

//Bad code
public void ProcessOrder(DateTime orderDate){
    var date = orderDate != null? orderDate: Datetime.Today()
}

//Good Code
public void ProcessOrder(DateTime orderDate =  DateTime.Today()){
    var orderDate = orderDate
}


06.  Avoid mental mapping , keep it easy to read 

        //bad code     
        var l = new []{"USA","Sri Lanka","India","Singapore"}
            for(int i=0;i<l.Count();i++){
                //code logic here
                var country = l[i];
                //code logic here
                 DoSomething(country);
            }

    //good code
            var countryList = new []{"USA","Sri Lanka","India","Singapore"}
            foreach(var country in countryList){
                //code logic here,
                DoSomething(country);
            }

07. Use Searchable name 

 //bad code
            var data = new { Name = "Kamal", Age = 34 };
           
    //good code
            var person = new Person
            {
                Name = "Kamal",
                Age = 42
            };

08.  Avoid Type Checking 

Always try to used strongly type object, 

public Path TravelToTexas(object vehicle)
{
    if (vehicle.GetType() == typeof(Bicycle))
    {
        (vehicle as Bicycle).PeddleTo(new Location("texas"));
    }
    else if (vehicle.GetType() == typeof(Car))
    {
        (vehicle as Car).DriveTo(new Location("texas"));
    }
}

public Path TravelToTexas(Traveler vehicle)
{
    vehicle.TravelTo(new Location("texas"));
}

//OR pattern matching
public Path TravelToTexas(object vehicle)
{
    if (vehicle is Bicycle bicycle)
    {
        bicycle.PeddleTo(new Location("texas"));
    }
    else if (vehicle is Car car)
    {
        car.DriveTo(new Location("texas"));
    }
}

09. Method should have single responsibility

//Bad Code
public void SendEmailToListOfClients(string[] clients)
{
    foreach (var client in clients)
    {
        var clientRecord = db.Find(client);
        if (clientRecord.IsActive())
        {
            Email(client);
        }
    }
}

//Good Code
public void SendEmailToListOfClients(string[] clients)
{
    var activeClients = GetActiveClients(clients);
    // Do some logic
}

public List<Client> GetActiveClients(string[] clients)
{
    return db.Find(clients).Where(s => s.Status == "Active");
}

10.   Avoid many function argument 

//bad Code
public void SendEmail(string title, string body, string ccAddress, string ToAddress, string Sender)
{
    // ...
}

public class EmailDate
{
    public string Title { get; set; }
    public string Body { get; set; }
    public string ToAddress { get; set; }
    public bool CCAddress { get; set; }
}

var config = new EmailDate
{
    Title = "ERROR CODE 001",
    Body = "TEST EMAIL BODY",
    ToAddress = "Baz",
    CCAddress = true
};
//good code
public void SendEmail(EmailDate emailData)
{
    // ...
}


11. Error Handling 

This is a another very important section, if system doesn't have proper error handling will cost for support and maintainability 

 Don't re throw same exception in the catch block, 

try

{
    // Do something..
}
catch (Exception ex)
{
    // Any action something like roll-back or logging etc.
    throw ex;
}

try
{
    // Do something..
}
catch (Exception ex)
{   
    throw ;
}

 

Don't ignore exception. 

//code

Use multiple catch block instead of if condition on the catch block 

//code


Don't leave out of comment on code base on leave com


you can find more details on below pdf 

Reference : Clean Code.pdf (itcollege.ee)