Geeknarrator

  • Home
  • Podcast
  • Blog
  • Serivce
  • Contact Us
Hit enter to search or ESC to close
post-header
computer science

Readable Code : Just like a fairy tale

admin
October 2, 2017

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

Share this on:
clean codecode formatDRY principlejava programmingreadable codeSOLID principle
Previous post
Dynamic Programming
Next post
Parallel Programming in Java (Part – 1)
Related Posts
Technology

Managing credentials with AWS KMS

admin
Jan 17, 2018
Placeholder Image
Technology

How Facebook earns money ?

admin
Oct 2, 2017
1 Comment
    kaivalya apte
    Dec 15, 2017 Reply

    Reblogged this on Geek Narrator.

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Recent Posts

  • Embracing Technical Leadership and the Architect Role: Insights from Venkat Subramaniam
  • Distributing SQL Databases Globally
  • Why is DynamoDB AWSome?
  • Designing Instagram, Linkedin, Facebook like applications
  • Test Driven Development with Frederik Banke

Recent Comments

  1. kaivalya apte on Software Engineering Interviews – 5 Red Flags
  2. Amitk on Software Engineering Interviews – 5 Red Flags
  3. Anurag Kumar on Software Engineering Interviews – 5 Red Flags
  4. Sylvia Boyle on CAP Theorem – Consistency, Availability and Partition Tolerance.
  5. Rajan on Smart and Stupid Alexa – My Experience
team

Brayan Olson

Art Director

It’s our job to get you the information you need, so you can make the most of your aviation investments.

Categories

  • computer science (18)
  • Interviewing (2)
  • kafka (2)
  • REST APIs (1)
  • Scalability (7)
  • streamprocessing (1)
  • Technology (26)
  • Uncategorized (3)

Recent Posts

  • Software Engineering Interviews – 5 Red FlagsMay 26, 2019
  • Recursion : Understand recursion with a simple exampleOctober 2, 2017

Popular Tags

algorithm AWS bigdata cap clean code computerscience Design pattern elastic elasticsearch framework functional programming functions highly scalable index integration testing internet Interview mistakes invertedindex Java java programming languages microservices money mongodb monolith multiprocessors new index nodowntime nosql old index optimisation Parallel programming partition tolerance positive functions postgresql integration testing postman collection for elastic search Predicate Preparing for interview programming Scala sharding software engineering Testing threads unit testing

Newsletter

newsletter signup

Get notified about updates and be the first to get early access to new episodes.

FAQ

Most frequent questions and answers
What is The GeekNarrator?

The GeekNarrator is a dynamic platform dedicated to sparking curiosity, excitement, and inspiration in the realms of Technology and Software Engineering. Its unique offerings include comprehensive and in-depth technical discussions led by industry experts, providing actionable insights for aspiring and established software engineers alike. The GeekNarrator is more than a resource—it’s a community committed to nurturing your inner geek, helping you leverage technology, and empowering you to excel in software engineering.

How do I collaborate?

If you want to do a paid collaboration, then shoot an email at speakwithkv@gmail.com. 

 

 

We are a tech startup, how can you help?

I’m a firm advocate for the idea that contemporary technology companies must actively engage in podcasting. It’s an excellent medium for articulating the challenges they’re addressing, elucidating the unique solutions they’ve developed, and cultivating awareness around the technology they’re leveraging. But above all, it’s a powerful tool for fostering a vibrant and engaged community.

I can be your ally in this venture. Let’s join forces to create not just an episode, but perhaps an entire series. Our discourse can revolve around the bedrock principles of software engineering and state-of-the-art technology, all while highlighting the remarkable features of your product. This collaboration promises to amplify your voice in the tech community, underscore the importance of your work, and illuminate the path to a tech-forward future.

I am a Software Engineer, how can I use your platform to become a better engineer?

In the field of Software Engineering, effective communication, collaboration, and engaging in deep discussions play pivotal roles. These skills are just as crucial as technical expertise when it comes to becoming a truly exceptional engineer. With this in mind, I create a series of podcast episodes that aim to assist you in honing these abilities, expanding your knowledge, and igniting your curiosity to engage in meaningful conversations.

By tuning into the podcast, you will gain valuable insights from experienced professionals, discover their diverse range of experiences, and be inspired to embark on your own exploration of software engineering. Furthermore, the episodes will equip you with practical techniques to enhance your communication skills, ensuring that your ideas are effectively conveyed and understood.

By actively engaging with the podcast, you will find yourself equipped with the necessary tools to excel not only in the technical aspects of software engineering but also in fostering productive collaboration, articulating your thoughts clearly, and facilitating profound discussions. Together, we will unravel the secrets of effective communication, collaboration, and the art of engaging in thought-provoking conversations, ultimately empowering you to take your engineering capabilities to the next level.

site-logo

Be Geeky!

Subscribe Podcast on:
Youtube
apple music
spotify
Google podcast
Get in Touch

speakwithkv@gmail.com

Twitter Linkedin

© 2023 — Produced by Geeknarrator

All rights Reserved.