Re: Control Flow Coding Style
jens bendig <[email protected]>
| Newsgroups | gmane.comp.programming.language-of-the-year |
|---|---|
| Message-ID | <[email protected]> |
Hi Avdi, I completely agree with your short-circuit-clauses. Also, with the Problematic return inside a deep conditional. Here, I would add a thing: Mostly, when you have a deep conditional in *any* Method, you have a Design-Problem that can be solved by some refactoring. The deep conditional often has to do with doing something at the wrong level of detail. The complicated descision will vanish or spread, if somewhere else in the code the right thing is done. However, I´d not just look for the return, but also for complicated conditions at all, you don´t need them. The third thing, the else-clauses: Right, In about every case you should be aware that you have the else-clause coded there. If you don´t write it down, the else-clause is implicitely coded by the following code. The only case where I don´t code the else is the short circuit-cause. Yours, Jens Am 28.04.2008 um 16:55 schrieb Avdi Grimm: > On Mon, Apr 28, 2008 at 4:55 AM, Michael Hunger <[email protected]> > wrote: > > 1) there _must_ be a single point of exit for each method > > For me the point of pragmatic compromise falls thus (and I'm assuming > we're only talking about method return, not exceptions): In general, > only one point of return. There are a couple of exceptions, though. > > 1. Short-circuit clauses at the beginning of methods: > > def foo(arg) > return nil if arg.some_special_case? > > # ... the meat of the method ... > end > > I like to keep these in a separate clause at the beginning of the > method, though; once the primary logic of the method begins, no more > short-circuit returns allowed. > > 2. Methods where there is a consistent and obvious pattern of returns: > > def bar(arg) > arg = transform1(arg) > return arg if arg.ready? > arg = arg transform2(arg) > return if arg.ready? > arg = transform3(arg) > return arg > end > > What I *don't* like to see is a method that has one obvious return at > the end, and then a second special-case return buried a couple layers > deep in conditionals. Those are the methods that lead to > head-scratching debugging sessions because you haven't noticed that > the method is exiting early. > > > 2) each if must have an accompanying else branch > > The longer I write code, the more I think this is a good idea. I > pretty habitually put in 'else raise "Should never get here"' clauses > in my code. Yeah, it's a little extra clutter; but the time savings > in catching bad assumptions early is worth it IMO. > > -- > Avdi > > Home: http://avdi.org > Developer Blog: http://avdi.org/devblog/ > Twitter: http://twitter.com/avdi > Journal: http://avdi.livejournal.com > > Dipl.-Phys. Jens Bendig motionDesign im Technologiepark Universität Bremen http://www.motionDesign.de [email protected] Fahrenheitstr. 1 28359 Bremen Tel. 49 -421 2208 311 nachmittags