Avoid nesting by handling errors first

Authors
  • Amit Shekhar
    Name
    Amit Shekhar
    Published on
Avoid nesting by handling errors first

I am Amit Shekhar, a mentor helping developers in getting high-paying tech jobs.

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.

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
    }

 }

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
}

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

You can connect with me on:

Read all of my high-quality blogs here.