Readable Code : Just like a fairy tale

Most software today is very much like an Egyptian pyramid with millions of bricks piled on top of each other, with no structural integrity, but just done by brute force and thousands of slaves. – Alan Kay

Writing code is simple. Yes, you read it right. It is simple, but writing code as readable as a fairy tale is an art.And art is not simple. Now why should we write readable code? Because our code is for humans first and machines later. If you are working alone that’s fine, but if you are working in a team (in most cases yes) you need to collaborate with your team members.

To achieve that, you need to write code which is easily understood by others.If your code is a puzzle for others, its not a good code. It might be working correctly, it might be very efficient but not readable.Now the chances are, your team member will still make some changes to your code without completely understanding and inject bugs.This could become a nightmare to debug, if even you don’t understand your code anymore 🙂 .

There are many aspects to write a Production level code :

  • Correctness – This is the basic requirement from your code. It should produce correct results.
  • Efficient – This is another important aspect which can lead to terribly performing software if not taken care well in advance.
  • Reusable – If your code is reusable it can reduce a lot of effort,lines of code and time to market.You should write code which can be consumed by others as a library or as a service.
  • Configurable – Making code configurable enables you to change the behavior of the software at runtime by just changing some configurations.This can be really helpful while enabling new features without redeploying, testing consumer behavior, disabling a feature when something goes wrong.
  • Readability – This is something which is a non-functional requirement, but at the same time very important.This is what we are going to discuss in this article.

There are many other aspects which I am not going to talk about here, but major ones are listed above.

So, lets talk about Readability in detail with some code examples.

What do you think about the below code ?

//
public class MyBadCode {
public static Customer getCustomer(String param){
if(param=null || param.length<1 && param.length>250) throw new Exception("Name is invalid");
Customer customer;
   try{customer = customerDAO.getCustomerByName(param);
return customer;
}catch(Exception e){
LOGGER.error("DAO Exception");
}
}

Is it a readable code ? Probably not. But wait, you can read it right ? That’s true, but Readability not only refers to you being able to read.It also means if you are able to understand the code. Above code is a bad code in many ways.

  • No comments at all.
  • Naming conventions not followed.
  • getCustomer is a very generic name for a method.As per the code it is considering “param” to be a customer name. So it is better to rename the variable to be “customerName”
  • Indentation has a big problem.It is small thing, but matters a lot when you are reading the code. Code should be properly indented.
param=null || param.length<1 && param.length>250
  • Above condition can be moved to a method named “isCustomerNameValid(name)” which is more readable.Why? because it better to read english words and understand rather than logical operations.

All the above improvements will result in the code below :

public class GoodCode {

  /**
   * This method finds a customer from the DB using customerName
   * @param customerName
   * @return
   * @throws Exception
   */
  public static Customer getCustomerByName(String customerName) throws IllegalArgumentException{
    
    if (isCustomerName_NotValid(customerName))
      throw new IllegalArgumentException("Customer Name is invalid");

    Customer customer = null;
    try {
       customer = customerDAO.getCustomerByName(customerName);
      return customer;
    } catch (Exception e) {
      LOGGER.error("Database layer exception occured",e);
    }
    return customer;
  }

  /**
   * This method checks if customer is valid or not.
   * @param customerName
   * @return
   */
  private static boolean isCustomerName_NotValid(final String customerName){
    if(Objects.isNull(customerName) || isCustomerNameLength_Not_InRange(customerName,1,250)){
       return true;
    }
    return false;
  }

  /**
   * This method checks if the customer name length is in the given range or not.
   * @param customerName
   * @param min
   * @param max
   * @return
   */
  private static boolean isCustomerNameLength_Not_InRange(final String customerName,final int min,final int max){
    return customerName.length() < min && customerName.length() > max;
  }
}

Above code is way better than the previous one, it uses proper comments to explain what the methods are intended for, it is modular hence more testable.It also uses method names that makes sense.There are many other improvements that can be done here, but the main idea here is make the code more Readable.

Some key points to be noted here are :

  • Use consistent indentation : We need to use consistent formatting and indentation across our code base.This makes developers life easy and the code more readable.
  • Use consistent naming convention : Naming conventions for classes, methods,variables,exceptions, interfaces etc need to consistent.Ideally we should try to name an entity based upon its intent. For methods the intent is its behavior, like getting a customer from DB, validating a customer etc.For model classes it refers to a noun .For example a Customer, Address, CustomerContact etc. For utility classes it can be named as a combination of the model and “utility” or “utils” as a keyword. ex CustomerUtils.
  • Use consistent comments : Comments are a very important part of your code.Put comments which are really helpful to navigate through the code. Adding obvious comments is not helpful.For ex :
//
//get customer by its name ---> (USELESS COMMENT)
getCustomerByName(customerName);
  • Group your code : Try to group your code as much as possible.Grouping can be done based on declarations of variables, method invocations, types of variables etc. Example below :
//Not organized
boolean isActive;
String customerName="John";
int age=10;
String customerLastName;
Customer customer = getCustomerByName(customerName);
long phoneNumber="9091288192";
isActive = isCustomerActive(customer);
if(isActive){
 //do something
}else{
 // do something else
}
CustomerAddress customerAddress = getCustomerAddressByCustomer(customer);

Above code is unorganized.Method invocations are mixed up with variable declarations, conditional logic etc.This can be organized by grouping as follows:

// Declare required variables
int age=10;
long phoneNumber = "9091288192";
String customerName= "John";

//Get customer address by customer object
Customer customer = getCustomerByName(customerName);
CustomerAddress customerAddress = getCustomerAddressByCustomer(customer);

//Perform task if active
if(isCustomerActive(customer)){
 //do something
}else{
 // do something else
}

  • DRY Principle : Don’t repeat yourself. Duplication of code may lead to bug, and fixing it, can become your worst nightmare if there is lot of duplication.Try to store/cache results as much as possible, which can save network calls, DB reads, and also avoid duplicate method invocations. Take a look at the example below :
Customer customer = getCustomerByName(customerName);
 
 //Perform task if active
if(isCustomerActive(customer)){
   //do something
}else{
   //do something else
}

//This can be moved to above condition.
if(isCustomerActive(customer)){
   // do something
}
  • Limit number of lines in each method : Try to limit the size of each method.Long methods can be very confusing, difficult to test and error prone.Writing big methods reduces the Readability of the code and makes it really difficult for someone to understand and debug the code.Try to limit the number of lines in a method by creating more meaningful methods.

Above practices are just few points which can be easily followed to make code more Readable. Anyone can code, but only Good programmers write readable code.

I would like to end this article with few programming quotes :

Before software can be reusable it first has to be usable. (Ralph Johnson)

If builders built buildings the way programmers wrote programs, then the first woodpecker that came along wound destroy civilization. (Gerald Weinberg)

Post your comments on the article for any improvement/correction required.I hope it was a Readable article 🙂 .

One thought on “Readable Code : Just like a fairy tale

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s