DEV Community

Boris
Boris

Posted on

Early return patterns

"First write the code for people, then for the machine."
I don't know who originally said this but it's legitasf.

How many times you saw some piece of code and like what!? What is this supposed to do?

One good tip that I accepted from a senior developer in my team is to use that early return statement which is my favorite thing if I have small to medium business logic inside my functions.

You have a function that does something bigger, and it does it well but not too well.

fun getListOfArticles(hasInternet: Boolean): List<Article> {
    if (hasInternet) {
    //big piece of code. Maybe some data manipulation before 
     //returning the list of Articles from the API.
    } else {
       return emptyList()
    }
 }
Enter fullscreen mode Exit fullscreen mode

This is OK, but if you want to make life easier for somebody else that will read your code in half a year we can use that early return pattern which comes in handy sometimes and it looks like this:

fun getListOfArticles(hasInternet: Boolean): List<Article> {
    if(!hasInternet) return emptyList()

    //Big piece of code here for manipulating the data
    return articles
 }
Enter fullscreen mode Exit fullscreen mode

This way is more intuitive to read "if there is no internet, just return an empty list of articles" or do whatever you need in your app. Just return early as possible and you will make your program fail fast.
That means:

  1. Easier to read
  2. Easier to spot code smell
  3. Easier to debug.

Here's one more interesting example using a happy path design

"The happy path for a function would be where none of the validation rules raise an error, thus letting execution continue successfully to the end, generating a positive response."

fun logIn(argument1: String?, argument2: String?, argument3: 
 String?) {
  if(argument1 != null || argument2 != null || argument3 != 
   null) {
  //do something and log in the user
    } else {
  // throw exception
  }
}
Enter fullscreen mode Exit fullscreen mode

Now happy path applied:

fun logIn(argument1: String?, argument2: String?, argument3: String?) {
 if(argument1 == null) throw Exception() //maybe throw different exceptions
 if(argument2 == null) throw Exception()
 if(argument3 == null) throw Exception()

  //do the happy path of the function here

}
Enter fullscreen mode Exit fullscreen mode

Some patterns that are considered as early return:

You have your own style of writing software but be aware that this is popular for a reason and it has a lot of benefits inside the codebase. It will force you to think more with that "TDD" mindset.

Top comments (0)