Say we have a function foo(), and a bool bar. The work foo does is of no use if bar is false. What is the most proper way to write foo()?
1
foo() {
if(!bar)
return;
doWork();
}
2
foo() {
if(bar)
doWork();
}
Option 1 has the aesthetic advantage that doWork() (ie, the rest of the function) is not indented, but the disadvantage that if you don't look at the early return statement, you may assume that doWork() is called every time you call foo().
In general, is it bad practice to code in style 1, or should it be a personal preference?
Some people will always say to you the "have a single exit point" mantra.
Sometimes, if you need to perform a specific operation on every exit point, it makes a lot of sense. I'd say it's crucial to keep sanity, in this specific case.
Now, if you doesn't have this need, I, personally, see no problem in just exiting as soon as you can and keeping the code on level of ident lower.
I've seen people wrapping the whole code in a do { ... } while (0); block just to keep the single exit point rule, using a break instead of a return. It drives me crazy. But it can be a useful device in some situation.
Overall, use common sense and use what makes more sense in your specific problem.