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.

Like
Reply

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

Like
Reply

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.

Like
Reply

To view or add a comment, sign in

More articles by Houssam Hamdan

  • .NET Code Reviews - Classes

    Few days ago, i started a series for code reviewing .NET applications.

    2 Comments
  • .NET Code Reviews - C#

    I am often asked to look into an existing code base to give the company an idea of the quality of the code. This…

    4 Comments
  • Pluggable Architecture

    In the .NET Application Architecture Guide , 2nd edition, Microsoft recommends implementing pluggable design to…

    3 Comments
  • SOA Simplified

    What exactly is Service Orientation or Service Oriented Architecture / Application? Simply, it is the decomposition of…

    1 Comment
  • Security-related HTTP Response Headers

    This page lists useful security-related HTTP headers. In most architectures, these headers can be set in web server…

  • Beacons - The Untold

    Recently, i conducted a research about the beacons technology. After playing around with one of the vendor's SDK and…

  • Big Data - Not yet defined

    In this article we will be defining the term Big Data. In fact we'll be presenting a number of different definitions in…

  • Big Data - The Perfect Storm

    This series is designed to give a broad understanding of Big Data, both to those who already have some understanding of…

  • ASP.NET Security Secrets

    Most Software Developers lack in security knowledge. They simply don't understand how our applications are attacked.

    8 Comments
  • The Single Responsibility Principle

    We'll begin by defining The Single Responsibility Principle (aka SRP) and demonstrating what are the problems when…

    2 Comments

Others also viewed

Explore content categories