The benefits of Early Returns

Returning early in a method is something that we have debated quite a bit at work, and what I see is that there reasons to return early and times to have a single return.  There are two reasons to return early one which prevents code from executing when it does not need to execute and the other is to make code more readable.  As for having a single return the main reason is for code readability but from a different aspect than returning early.

So to demonstrate the point I have included the same method written with return early and on with a single return here.

In this comparison I have simple code that is checking if a SMTP mail message is valid.  I am checking that the message is not null, there is at least one From address, one To address, and something in the body.  This might be a bit of an extreme example but it does work to illustrate the point that early returns can make the code more readable.  With regard to efficiency the early returns make the code more efficient in that there is no need to continue execution if one of the early message checks fail.  Using this example, if the From address is not valid (not containing an @ symbol) then the code will return a false immediately rather than continue checking running the code.

Something to note with this comparison, the method using the early returns has a total of 27 lines whereas the method using the single return has 46 lines.  So unless you are being paid by the line of code when writing methods such as this, it is better to have early returns.

One additional note, if you code looks like this….

you need to do something else because this is just bad (I was emailed this code and I am not sure of its original source).