There are many ways to achieve the same result using different language features. Then you should choose the version that most clearly shows your intent - it's all about readability.
Using "else" vs. early-abort
Use else
to express "There are two similarly-ranked alternatives".
If the two branches created by an if
condition are comparable in rank / probability, I prefer to have both indented (placed in its own sub-block), using else
in-between.
If one branch is a special situation allowing an early abort of the main control flow, and the other branch is the normal continuation, then I prefer an early-abort keyword like break
, return
or continue
, depending on the context. This way, the normal continuation stays on the same indentation level as the code before the condition, indicating that it's the normal sequence of steps.
Early-abort using "return"
Use return
to express "I'm finished (early) with this function".
This one is very popular, because it's easily understood. If you see the return keyword, you know that this leaves the currently-executing method. You don't have to search for the place where to continue. I use this quite often.
Early-abort using "break"
Use break
to express "I'm finished (early) with this loop".
This leaves the currently-executing loop. It's not that easily readable: you have to look for the next enclosing for
/ while
/ do-while
loop, and you should keep in mind that none of the looping elements (e.g. i<10
or i++
) is executed any more (ok, you'd expect that).
Early-abort using a labeled "break" (Java)
Use break label
to express "I'm finished (early) with the named block".
This is valid only inside a block with that label. There aren't many situations where you'd need that, so it's quite unusual to such a degre that many developers don't even know that this construct exists. To understand the code, you have to search backwards for the label, and then skip the block forward to reach the continuation point.
Early-abort using "continue"
Use continue
to express "I want to immediately jump to the next iteration".
This leaves the currently-executing loop iteration. It's not easily readable: you have to look for the next enclosing for
/ while
/ do-while
loop, and you should keep in mind that the looping elements (e.g. i++
and i<10
) are executed before the next iteration starts. I've rarely used that.
So, choose the one that best expresses the intent of the conditional situation.