Reduce Your Nesting

13 Jul 2012. comments

A key aspect of software development is making the code base maintainable. If the code is hard to read or understand it corresponds to an increase in maintenance cost.

Nesting occurs when you open up a new code block. This comes in various forms depending on the language, but its typically your conditional branching and looping. For example, here’s a lot of nesting:


public String getNameFromDatabase(string id) {
  if(id != null) {
    if(id.trim() != "") {
      Person person = this.database.load(id);
      if(person != null) {
        if(person.Name != null) {
          return person.Name;
        } else {
          return "";
        }
      }
    }
  }
  return "";
}

The human brain can only keep so many things in mind at a time, and usually the more contexts that you enter that need to be kept in your head, the more likely it is that you’ll get lost or make mistakes.

The solution to the above example is often to use early exits.

public String getNameFromDatabase(string id) { 
  if(id == null) {
    return "";
  }

  if(id.trim() == "") {
    return "";
  }

  var person = this.database.load(id);
  if(person == null) {
    return "";
  }

  if(person.Name == null) {
    return "";
  }

  return person.Name;
}

Doing this improves readability and maintainability because you only have to keep at most 1 context in your head at a time. Once you’ve moved beyond each section you can safely forget it and move on to the next one.

Another common one that junior developers make:

public boolean getFoo() {  
  if(thingX == true && thingY == true) {  
    return true;  
  }  
  return false;  
}

Here’s how we can make it better:

public boolean getFoo() {
  if(thingX && thingY) {
    return true;
  }
  return false;
}

But it can still be even better. Here’s how:

public boolean getFoo() {  
  return thingX && thingY;  
}

It’s a contrived example of course, but it illustrates the point. Now there’s no nesting, no unnecessary comparisons, and it’s faster to read and understand. As with all practices and approaches this needs to be considered on a case by case basis because there are certainly cases where a single line return statements actually hurts readability, especially as the branch clause grows larger.

comments

Tagged: maintainability java software craftsmanship

2017 Ben Lakey

The words here do not reflect those of my employer.