Clean Code is an Art
Good Code vs Bad Code, “A code, understood by the machine but not human is an example of Bad code even it is giving the right output whereas a code, understood by machine and human both is the Good code”. So I would say, An expert may write code but only an artists (Code Artist) can write good code. Remember “writing a clean & good code is nothing less than an Art”.
Writing clean code is the equal responsibility of everyone in the team. Here I’m going to put some best industry practices to make your code clean and I’ll also put some points which helps to make your code clean based on my experiences so far.
Clean Code best practices:
1. Meaningful Names: Meaningful & Readable names in programming are as important as your name. Name is the first identity which speaks a lot i.e. a human name itself reveals its gender, religion, country/state (many cases) etc. And if you come to India, a person name can itself reveal about person birth place too. So isn’t it would be good to give a good name, i.e.
int c = 0; \\counter value
Here in above example, variable name c & dt doesn’t reveal anything hence it would be much better if we do this, as this says what is this variable for:
int counter = 0;
Overall goal is, name itself should speak about the purpose and the same applicable to any objects (function/class/variable) name in your program.
For classes and objects, make sure it is a noun or noun phrase and avoid using verbs or adding unnecessary prefix or suffix. i.e.
}is better thanclass CustomerDetails
Similarly for functions, the name of the function must tell the purpose of the function. i.e.
public DateTime GetPlannedScheduledDate()
}is better than the below function here:public DateTime GetDate()
So please mind it and don’t be lazy for choosing a good name.
2. Functions: Function is the another key tool to create your code art. Yes, what I mean is Your function should not only have a meaningful name but it should also be short and must be doing exactly the name says. So the first thumb rule for your functions is, “they should be small”. and the second rule of functions is that “they should be smaller than that”.
So Never hesitate to create a private method instead of adding few extra lines of code in the method which is not justifiable by the function name and deviate you from the function purpose.
Also I would recommend you to strict with Single Responsibility Pattern here while writing your function.
3. Comments: A code comments is very helpful to tell others about what code is doing but what if your object name and function name itself are doing that then why to comment. I won’t say commenting is bad but I guaranteed you that over the period your comment will turn to the bad and it happens because most of time during maintenance code changes but people ignore comments to update.
Is that mean, commenting is bad, of course not but if you have to do it only when it is necessarily important. i.e.
//Bad comments example//Comment:Checking if an account is currently active
if(!account.IsDeleted && account.AvailableBalance > 500 && account.lastTransactionDate > DateTime.Now.AddMonths(-3))
above code here can be refactored and comments can be avoided more meaningfully as:
}private bool checkIfAccountActive()
return !account.IsDeleted && account.AvailableBalance > 500 && account.lastTransactionDate > DateTime.Now.AddMonths(-3);
This refactored code looks cleaner and no comment required to understand the code here.
but there are some places where you must have to comment to avoid code being messy with any accidental changes. i.e.
//This is our best attempt to get a race condition by creating large number of threads.
for (int counter = 0; counter < 2500; counter ++)
//Code which creates a thread with every loop here.
Above code tells clearly the reason behind loop value to 2500. In this cases, comment is justifiable.
There are other cases also where comments are justifiable like, Legal comment (i.e. Copyrights), domain specific information (which can help programmer why certain things are written in that way) etc.
4. Code Formatting: This helps your code looks cleaner and it increases readability. Use new line space, tab space, curly braces (event if it single line if statements) etc. to format your code.
Also try to group & order the functions like public functions comes first and then private functions in a order it’s been used.
5. Lengthy Function Parameters: I never seen any strict guidelines to limit the no. of parameters in functions but lengthy or more parameters affects the code readability. Hence you must avoid to limit it as short as possible.
6. Error Handling: This is another key area where if you don’t pay much attention then it cost your program’s performance & security, but if you handle it well then it will not only help you in performance & security but also helps to debugging code when there is an error.
So key recommendation here is, use Exception Handling (try, catch, finally) efficiently and log your exceptions.
I would suggest read this article here Exception Handling Techniques & Tricks C# to know the best practices of Exception Handling.
7. Unit Tests: Unit test is extremely important to safe guard your code with any accidental change which can break the feature/purpose, this is only possible if your code is written in such a way. So before writing code, first ask yourself, can you write the unit test for this piece of code and do it. If not, it is time to refactor the code.
Now lets see few techniques which can help any teams to force to follow the above guidelines to make the code better and cleaner.
- Peer Code Review: This is best techniques to clean your code. The more persons review your code, you get more ideas to make your code better. It is a human tangency to miss small things when you are on a problem to solve but those small things may affect the code readability, performance or security. Hence this is where Peer Code Review helps.
- Keep yourself updated: Whatever technology or language you use, it is very important to keep yourself updated so that you can use the latest technology or features to make your code better & better. Hence thumb rule here, keep learning.
- Use libraries (nuget packages): There are many useful open source libraries available to do which you might want to do so I recommend to use them instead of reinventing the wheel by your own. i.e. for data operations in .net there is a library called Dapper which is very useful”, so I recommend to use this instead of writing the whole piece from connection management to data management etc.
At the same time, Be careful also while choosing the libraries and you must read the licenses or the terms & conditions.
That’s all. Hope this helps, Happy reading.