akmadhwa.com

The Early Return Pattern

The first time i saw this pattern is in a Javascript repositories and i don’t know actually it a pattern and they use heavily in the codebase. I start to use it after i need to maintain an old codebase where it contain a lot of nested if else condition that you can never think of. After that i google on how to clean nested if else block and i found this pattern which is super useful.

The Pattern

It is a simple pattern but very useful and important pattern to know. I have been using this in all of my code and the benefits is a lot especially it make your code readable.

There are many reasons that you should use this pattern over using else statements.

Let dive straight into example. The examples are in PHP syntax but relevant to any language that allows multiple return statements

1function getPromocodeValue($promocode)
2{
3  if($promocode === 'hello') {
4    return 10;
5  } else {
6    return 0;
7  }
8}

The return early suggest to be like this

1function getPromocodeValue($promocode)
2{
3  if($promocode === 'hello') {
4    return 10; // Early return 
5  }
6
7  return 0;
8}

Thats it. Maybe with this code it not look like much, but you can see the difference in nested if else which have a lot of condition going on.

Simplifying the nested if/else loop

For example;

 1function getPromocodeValue($promocode, $country)
 2{
 3  if($promocode === 'hello') {
 4    if($country === 'US') {
 5      return 30;
 6    } else {
 7      return 10;
 8    }
 9  } else {
10    return 0;
11  }
12}

With Early returns

 1function getPromocodeValue($promocode, $country)
 2{
 3  if(
 4    $promocode === 'hello'
 5    && $country === 'US'
 6  ) {
 7      return 30;
 8  }
 9
10  if($promocode === 'hello') {
11    return 10;
12  }
13
14  return 0;
15}

To me with early return, the code are much cleaner and more readable. The condition is very clear and you can quickly understand what the condition do.

Additional Advantages

Here’s another way in which this pattern will make your code cleaner. The pattern forces your functions to do only one thing. If you know the “clean code” principles, you know that breaking your code to many short functions that only do one thing is the way to go. Many times developers have trouble employing the “return early” pattern because their functions are doing many things, and in that case you cannot just return in the middle of the function. If the “return early” pattern cannot be employed in a function it’s a good indicator that this function is not doing one thing and needs to be broken down

#programming   #clean-code   #php  

Reply to this post by email ↪