Clean Code
Let me start by [Marin Fowler] quote about clean code.
"Any fool can write code that a computer can understand.
Good programmers write code that humans can understand."
It is surprising how few words can illustrate what clean code is. Writing code human can understand. Period.
Often times, we as developers find ourselves in front of code written by others. We always fail to understand it thus ended completely refactoring the code unless we are lucky in copy paste operations.
We often wish we had the skills to write understandable and easy to maintain code which will bring us great satisfaction. I consider myself newbie in writing clean code but nevertheless, took the decision to share with you what i have learned so far in an attempt to make better quality software in our beautiful industry.
So, lets start with dirty and clean code examples without wasting your time.
1. Boolean names should sound like true/false questions
Dirty
var open;
var login;
Clean
var isOpen;
var loggedIn;
2. Booleans Comparison
Dirty
if(loggedIn == true) {};
Clean
if(loggedIn) {}; // be implicit
Dirty
if(!isNotLoggedIn);
Clean
if(loggedIn) {}; // stay positive
3. Stay Elegant
Dirty
int registrationFee;
if(isSpeaker){ registrationFee = 10;} else { registrationFee = 50;};
Clean
int registrationFee = isSpeaker ? 10 : 50; // more elegant
Dirty
if(employeeType == "manager") // error prone
Clean
if(employee.Type == EmployeeType.Manager) // intellisense, no typos
4. Avoid Magic Numbers
Dirty
if(status == 2) {} // like magic, few can explain
Clean
if(status == Status.Active) {}
Dirty
if(age > 21) {}
Clean
const int legalDrinkingAge = 21;
if(age > legalDrinkingAge) {}
5. Avoid Large Methods
Strive to write each logic in a separate function. Avoid fat methods that are hard to maintain. Breaking up large methods into smaller methods can increase readability and maintainability. Remember, a method should do one thing and do it well.
6. Return Early Principle
Use a return when it enhances readability... In certain routines, once you know the answer…not returning immediately means that you have to write more code.
[Steve McConnell], “Code Complete”
Dirty
Clean
7. Watch out for Flag Arguments
Watch out for side effects when naming your method:
- ValidateUser() shouldn’t save.
- RegisterUser() shouldn’t send an email.
Dirty
private void SaveUser(User user, bool emailUser)
{
//save user
if(emailUser)
{
//email user
}
Clean
private void SaveUser(User user)
{
//save user
}
private void EmailUser(User user)
{
//email user
}
8. Avoid Comments
This is me to the left during a technical interview @:
Useless Comments as follows:
int i=1; // Set i = 1
var user = new User(); // Instantiate a new user
/// <summary>
/// Default Constructor
/// </summary>
publid User()
{
}
/// <summary>
/// Calculates Total Charges
/// </summary>
private void CalculateTotalCharges()
{
// code here
}
// Assure user's account is not active
if(user.Status == 2)
if(user.Status == Status.Inactive) // Cleaner
Conclusion
Writing clean code brings happiness to software developers. There is nothing more productive than a happy developer.
"Special thanks to Cory House from www.bitnative.com"
Thanks Houssam Hamdan, it is really best practice.
Informative.
More cleaner one for if(employee.Type == EmployeeType.Manager) // intellisense, no typos if(employee.isManager()) let objects have enough methods to encapsulate at role level
+1 for comment from Raja Nagendra Kumar
Offshore teams are normally chosen on cheap hourly cost, rather than skill or on total cost of solution. This is adding to mess each hour in the form of messy code. Such is the primary cause for Technical Debt. Wish Marin Fowler teach CEO's on how to write and sign right business contracts first. Unless this change happen at business level, clean code, offshore innovation, end value are only myths.