A simple return

After a long break, caused by various inevitable visits to doctors and hospitals, I happily present the next article. I also consider the title to be somewhat fitting. Today, I want to talk a little bit about return statements. The article is aimed at newcomers to programming, but maybe it is also helpful for one or two experienced developers.

I am a big fan and evangelist of the principle of having a single exit point. This means that there is always one – and only one – exit point (read: return) in any method, ideally at its end. To my mind, this enhances the flow of reading and reduces the complexity of code. A lot. I would like to give an example (it is written in C# but applies to any other language) that I recently encountered.

I found a somewhat lengthy method that ended with the following lines:

Doesn’t look that bad, does it? However, this can still be greatly enhanced:

Ok, now let’s have a look at what we gained by rewriting the code:

  1. We removed four lines of code.
  2. We reduced nesting by one level.
  3. We removed one return.

That’s a lot of removing at relatively little cost. I want to show you how you can get from the first piece of code to the second, optimised piece of code.

At first, we will add an additional else block. That makes things even worse, but it will help us to accomplish our task.

Then we will invert the if-condition (ReSharper comes in handy, but you can also manually invert it).

It is already easier to read, because the if-condition is not negated anymore and it is obvious what happens in which block. Next, we will change the return in the if-block.

What happened? We replaced null by returnValue, because returnValue is null in this case. Sounds silly, but it will also help us in the next step.

We removed equivalent code, similar to the distributive property that we know from math lessons long ago, from both the if- and the else-block and put it at the end of the method. Since the if-block is empty and all the important things are now within the else-block, we will invert the if-condition once more.

Now the else block is empty and has therefore become redundant. Time to remove it.

The only things that is left to do is to merge the two if-conditions with &&. Nesting depth is reduced by one and the code is now exactly the same as the second example above.

Repeat these steps a few times and you will understand the concept behind them. You will then be able to easily recognise similar pieces of code that can be simplified or rewritten. Whether you share my view of single exit points or disagree completely, please tell me in the comments.

On that note, happy coding!

Leave a Reply

Your email address will not be published. Required fields are marked *