DEV Community

Cover image for How to structure your code for readability
Dan Bar-Shalom
Dan Bar-Shalom

Posted on • Edited on

How to structure your code for readability

When writing code, it is often tempting to wrap the main flow inside multiple if statements in order to validate that certain conditions are met.
For example, let's say I'm writing a simple method that returns the length of a string. It might look like this:

function getLength(str) {
  if (typeof str === 'string') {
    return str.length()
  }
  throw new Error('parameter must be a string')
}
Enter fullscreen mode Exit fullscreen mode

While this guards against unexpected parameter types, the main flow is enclosed within an if statement. A more refined approach looks like this:

function getLength(str) {
  if (typeof str !== 'string') {
    throw new Error('parameter must be a string')
  }

  return str.length()
}
Enter fullscreen mode Exit fullscreen mode

On the surface, the distinction may appear subtle, yet the structure of the code makes the main code flow more readable.

This advantage becomes even more apparent when there are multiple exclusion flows. You can turn this nested structure:

function foo() {
  if (/*condition A*/) {
    if (/*condition B*/) {
      if (/*condition C*/) {
        /*main flow*/
      }
      /*handle !condition C*/
    }
    /*handle !condition B*/
  }
  /*handle !condition A*/
}
Enter fullscreen mode Exit fullscreen mode

into this:

function foo() {
  if (/* !condition A */) {
    /* 
    handle !condition A 
    return
    */
  }
  if (/* !condition B */) {
    /* 
    handle !condition B 
    return
    */
  }
  if (/* !condition C */) {
    /* 
    handle !condition C 
    return
    */
  }

  /*main flow*/  
}
Enter fullscreen mode Exit fullscreen mode

The result is cleaner and more readable code, easier to understand and maintain.

Top comments (2)

Collapse
 
franckpaul profile image
Franck Paul

The 2nd example is not correct as whatever the condition A, B or C are, the main flow will be process, and it is not the case in the 1st example.

Collapse
 
danbars profile image
Dan Bar-Shalom • Edited

You are correct, thanks.
I've added return in each if block