Avoid nesting by handling errors first

amitiitbhu

Amit Shekhar

Posted on September 23, 2022

Avoid nesting by handling errors first

Hi, I am Amit Shekhar, Co-Founder @ Outcome School • IIT 2010-14 • I have taught and mentored many developers, and their efforts landed them high-paying tech jobs, helped many tech companies in solving their unique problems, and created many open-source libraries being used by top companies. I am passionate about sharing knowledge through open-source, blogs, and videos.

In this blog, we are going to learn one of the coding best practices which is how avoiding nesting by handling errors first increases the readability.

This article was originally published at Outcome School.

The best way to learn this is by taking an example.

First, let's see the nesting in which we do not handle the errors first which is not a good practice in coding.

fun getComments(postId: Long, pageNumber: Int, limit: Int) : List<Comment> {

    if (postId != null) {

         if (pageNumber >= 0 && limit <= 100) {

            val comments = // fetch comments from database

            if (comments == null) {
                // handle error and return
            } else {
                return comments
            }

         } else {
             // handle error and return
         }
    } else {
        // handle error and return
    }

 }
Enter fullscreen mode Exit fullscreen mode

You can see that as we have not handled the errors first, it has led to the nesting and ultimately less readable.

Now, let's rewrite the above code by handling errors first to avoid nesting which is a good practice in coding.

fun getComments(postId: Long, pageNumber: Int, limit: Int) : List<Comment> {

    if (postId == null) {
        // handle error and return
    }

    if (pageNumber < 0) {
        // handle error and return
    }

    if (limit > 100) {
        // handle error and return
    }

    val comments = // fetch comments from database

    if (comments == null) {
        // handle error and return
    }

    return comments
}
Enter fullscreen mode Exit fullscreen mode

If we compare both codes, we can clearly see that the latter one is more readable.

This is how avoiding nesting by handling errors first increases the readability.

That's it for now.

Thanks

Amit Shekhar

Co-Founder @ Outcome School

You can connect with me on:

Read all of our blogs here.

💖 💪 🙅 🚩
amitiitbhu
Amit Shekhar

Posted on September 23, 2022

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

Sign up to receive the latest update from our blog.

Related