Avoid nesting by handling errors first

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

I am Amit Shekhar, Co-Founder @ Outcome School, 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.

Join Outcome School and get high paying tech job: Outcome School

Before we start, I would like to mention that, I have released a video playlist to help you crack the Android Interview: Check out Android Interview Questions and Answers.

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.

Prepare yourself for Android Interview: Android Interview Questions

That's it for now.

Thanks

Amit Shekhar
Co-Founder @ Outcome School

You can connect with me on:

Follow Outcome School on:

Read all of our high-quality blogs here.