How to structure your code for readability

danbars

Dan Bar-Shalom

Posted on January 22, 2024

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.

๐Ÿ’– ๐Ÿ’ช ๐Ÿ™… ๐Ÿšฉ
danbars
Dan Bar-Shalom

Posted on January 22, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

ยฉ TheLazy.dev

About