Sometimes I like to use early return statements to prevent nesting if statement, which I find makes for less readable code.
I am wondering if there is any objective or overwhelming general consensus as two which of the following patterns is better practice? I don't think this is a subjective question, since what I am really asking is there a near objective preference.
void func() {
if (a) {
do b
}
else {
do c
}
}
or
void func() {
if (a) {
do b
return;
}
do c
}
I would opt for the first version. I was actually given a lengthy explanation several years ago regarding this.
The two examples, as your wrote them now, are functionally identical. If the
a
condition be true, then the logic in the firstif
condition will execute, and the function will return. However, have a closer look at the second scenario:Right now, should the first
if
fire, the function would return, otherwisec
would execute. However, consider that at some point down the line a programmer decides to refactor the method for some reason. If he were to take out thereturn
statement, then the logic forc
would also execute ifa
were true. This may seem far-fetched, but it could happen more easily than you might think. On the other hand, if you use a fullif-else
, then even a refactor of theif
condition would never result in thec
logic evaluating at the same time.Frankly, I recommend the second one.
The first is better. Simply put,it helps another developer to understand that c compiles because the condition is false. It also prevents other people from making damaging changes to your code. That said,they are both correct and would both work just fine