DEV Community

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

Posted on • Edited on

4 1 1

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.

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

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

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay