Re: Control Flow Coding Style
"Clinton R. Nixon" <[email protected]>
| Newsgroups | gmane.comp.programming.language-of-the-year |
|---|---|
| Message-ID | <[email protected]> |
On Mon, Apr 28, 2008 at 4:55 AM, Michael Hunger <[email protected]> wrote: > 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 > 2) each if must have an accompanying else branch I think both you and your colleague have good points, and Jereon hit one on the head. The idea that there has to be one single point of exit is wrong-headed, but ideally, your methods should be short and simple enough that that is the usual case. Why is it wrong-headed? For the reasons you mentioned: you should fail early, and should use guard clauses to handle non-viable input. In addition, the idea of a "result" variable has always struck me as wrong-headed. Minimizing the number of variables in a program is usually a good idea, and the distance between when a variable is set and when it is used is often proportional to the chance there's a bug involving that variable. If you know the return value at any point in your method, I find it smart to return it then, but again, if you have simple, well-written methods, most will only have one point of return anyway. -- Clinton R. Nixon Senior developer | Viget Labs o: 703.891.0670 x7511 | f: 703.832.0341 We build web business. Learn more: http://www.viget.com Keep up with our Four Labs blog: http://blog.viget.com