Re: Control Flow Coding Style
"Jeroen Wenting" <[email protected]>
| Newsgroups | gmane.comp.programming.language-of-the-year |
|---|---|
| Message-ID | <[email protected]> |
--- In [email protected], "Michael Hunger" <pragmatic@...> wrote: > > I recently looked at a code review method which is based on rigid rule > checking. > Such systems are almost universally incorrect ;) > Two rules bothered me so I started a heated discussion with a colleague. > I'd be interested in your opinions. > > 1) there _must_ be a single point of exit for each method Nice in theory, wrong in practice. > 2) each if must have an accompanying else branch > Not needed if each if is wrapped as a block, even if it's a single statement. So no ... if (x) y; ... but if (x) { y; } ... > My colleagues view: > Both are right. > It simplifies the maintainability and the ability to add new aspects to a > program to have a single point of input and output. > Return is a kind of goto and should be avoided (create spaghetti code) > He's right in theory, but too rigid. Ideally a method should have single point of NORMAL exit. Abnormal termination should in that case be through an exception mechanism rather than return statements. > My view: > Both are overengineering (if enforced). > * fail fast > * simplify control flow multiple exit points make the control flow look easier from within the method, but can make it harder to track from outside. Of course if you have well written methods they tend to be short and have a single return point because they only do one thing and do it well. Take a case statement. I've seen way too many cases where people use a return statement in each branch to break out of the case and the method in one go. That's bad practice, and leads to others dictating strict rules about having only one return statement per method. Instead you should set the return value, use a break to exit the case, and return the value after the case statement ends. Jeroen Wenting