Tuesday, 19 April 2022

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”.

int c = 0; \\counter value
DateTime dt;
int counter = 0; 
DateTime systemGeneratedDate;
class Customer
{
}
is better thanclass CustomerDetails
{
}
public DateTime GetPlannedScheduledDate()
{
return plannedScheduledDate;
}
is better than the below function here:public DateTime GetDate()
{
return plannedScheduledDate;
}
//Bad comments example//Comment:Checking if an account is currently active
if(!account.IsDeleted && account.AvailableBalance > 500 && account.lastTransactionDate > DateTime.Now.AddMonths(-3))
{
//code logic
}
if(account.checkIfAccountActive())
{
//code logic
}
private bool checkIfAccountActive()
{
return !account.IsDeleted && account.AvailableBalance > 500 && account.lastTransactionDate > DateTime.Now.AddMonths(-3);
}
//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.
}
  1. 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.
  2. 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.
  3. 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.

No comments:

Post a Comment