I am here to talk about better coding practices which I learned over time. Typically, we realize something better once we understand that the way we coded it is now putting some constraint or accommodating new changes are getting messier.
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.
Let’s start by putting some fundamental questions.
What is an effective code?
As per my point of view, an effective code should have the following characteristics.
- It should be clean/crisp and yet complete.
- It should be scalable and reusable with minimum efforts.
- Until coding/naming convention is not explicitly customized for any project, it should follow default coding convention suggested by community tools like StyleCop/ FxCop / Resharper etc.
Why is effective code important?
Writing effective code is extremely important in any enterprise software development. Below are some of the points emphasizing the importance.
- It helps to understand better when re-visiting the code.
- It helps reviewer to understand the code easily.
- It helps when someone else fixes the bugs.
- It helps when someone tries to reuse the code.
How to write effective or quality code?
Let’s discuss some of the guidelines as follows.
- Keep crisp and yet complete logic
Please look at all three approaches below to understand it.
Example-1 (Bad code)
- if (i % 3 == 0 && i % 5 == 0)
- {
- Console.WriteLine("HiPrakash");
- }
- else if (i % 3 == 0)
- {
- Console.WriteLine("Hi");
- }
- else if (i % 5 == 0)
- {
- Console.WriteLine("Prakash");
- }
- else
- {
- Console.WriteLine(i);
- }
Example-2 (Good code)
- string output = "";
- if (i % 3 == 0) { output = "Hi"; }
- if (i % 5 == 0) { output = output + "Prakash"; }
- if (output == "") { output = i.ToString(); }
- Console.WriteLine(output);
Example-3 (Better code)
- string output = string.Empty;
- if (number % 3 == 0)
- {
- output = "Hi";
- }
- if (number % 5 == 0)
- {
- output += "Prakash";
- }
- if (string.IsNullOrEmpty(output))
- {
- output = number.ToString();
- }
- return output;
As you can see that final approach (Example-3) is crisp, clean, and complete.
- Use meaningful method names
Keeping meaningful names is very important so that the new users can get sense of the functionality just by looking at the method names.
Example-1 (Bad code)
- public int ReturnOutput (string name)
- {
- int id = -1;
-
- return id;
- }
Example-2 (Good code)
- public int GetEmpId(string name)
- {
- int id = -1;
-
- return id;
- }
Example-3 (Better code)
- public int GetEmpIdByName(string empName)
- {
- int empid = -1;
-
- return empid;
- }
As you can see, the Example-1 doesn’t give any sense of what this method is supposed to do however the later examples are taking care of this. The Example-3 even takes care about logical variable namings.
- Refactor the code whenever and wherever possible
Refactoring of code is very important in keeping the code clean and to increase the modularity and reusability of code.
Example-1 (Bad code)
- public void PrintPrimeNumbersTillHundred()
- {
- for (int number = 1; number <= 100; number++)
- {
- int i;
- for (i = 2; i < number; i++)
- {
- if (number % i == 0)
- {
- break;
- }
- }
- if (i == number)
- {
- Console.WriteLine("Number {0} is Prime", i);
- }
- }
- }
Example-2 (Good code)
- public void PrintPrimeNumbersTillHundred2()
- {
- for (int i = 1; i <= 100; i++)
- {
- if (IsNumberPrime(i))
- {
- Console.WriteLine("Number {0} is Prime", i);
- }
- }
- }
-
- private static bool IsNumberPrime(int number)
- {
- int i;
- for (i = 2; i < number; i++)
- {
- if (number % i == 0)
- {
- return false;
- }
- }
- if (i == number)
- {
- return true;
- }
- return false;
- }
As you can see in Example-1, the logic of prime number is not factored, hence if there is a need to reuse it, that's not possible. However, Example-2 takes care of it by factoring it to new method.
- Use Auto-Implemented Properties
Unless there is some custom logic needed in getter/setter or you are developing for less than .NET 3.0 framework (although it’s unlikely), go for auto auto-Implemented properties instead of creating them in traditional way using private variable.
Example-1 (Bad code)
- private string empId;
- public string EmpId
- {
- get
- {
- return empId;
- }
- set
- {
- empId = value;
- }
- }
Example-2 (Good code)
- public string EmpId { get; set; }
As you can see that auto implemented properties (in Example-2) provide clean way of declaration.
- Use object initializer
Starting from .NET 3.0 onwards, go for object initializer instead of traditional way of first creating object and then assigning values.
Example-1 (Bad code)
- Employee emp = new Employee();
- emp.EmpId = 101;
- emp.EmpName = "Prakash";
- emp.EmpCity = "Satna";
Example-2 (Good code)
- Employee emp = new Employee() { EmpId = 101, EmpName = "Prakash", EmpCity = "Satna" };
Clearly, object initializer provides crisp syntax to keep code clean.
- Follow logical ordering of members
It’s easy to navigate members when they are placed in logical order. Declare all member variables at the top of a class followed by methods. Also, keep private members first, followed by Public. Just to add - if you are using tools like StyleCop etc, these things are enforced by default.
Example-1 (Bad code)
- public class Employee
- {
- public int EmpId { get; set; }
- public void GetSalaryDetails()
- {
-
- }
- private DateTime EmpDateOfBirth;
- public string EmpName { get; set; }
- }
Example-2 (Good code)
- public class Employee
- {
- private DateTime EmpDateOfBirth;
- public int EmpId { get; set; }
- public string EmpName { get; set; }
- public void GetSalaryDetails()
- {
-
- }
- }
I hope you would agree that in Example-2, it’s easier to navigate to members.
- Avoid using very short abbreviations
Using very short names sometimes doesn’t give the sense of their parent object and hence is confusing. Below are the examples of short and recommended names.
Example
- ProductSales prSal;
- ProductSales productSales;
- Use casing properly
Unless explicitly specified, use pascal casing for classes and method names and camel casing for method arguments and local variables. Below is the example of pascal casing (ProductSales, GetSalesProfitByMonth) and camel casing (monthCode).
Example
- public class ProductSales
- {
- public void GetSalesProfitByMonth(int monthCode)
- {
-
- }
- }
- Use singular name
Try to use singular name for Class/Interface/Enum. Also prefix interface with I.
Example
- public enum Color
- {
- Red,
- Green,
- Blue
- }
-
- public interface IProductSales
- {
-
- }
And last but not least!!
- Review! Review! Review!!
Code review is very important in any successful software development. Code review helps in early detection of any code or design anomaly and can potentially minimize the number of bugs reported in the QA phase.
Conclusion
In this article, we have gone through some of the common coding mistakes and ways to address them. We have also gone through code snippets for them in order to understand the better and effective coding style.
Hope you liked the arrticle. I look forward to your comments/suggestions.