case/switch statement?

Peter Hansen peter at engcorp.com
Mon Jun 13 04:06:13 CEST 2005


Chinook wrote:
> On Sun, 12 Jun 2005 17:19:06 -0400, Peter Hansen wrote:
>>Case statements are actually more suitable in many cases even when 
>>performance is not a goal for reasons of *readability*.
>>
>>When reading an if statement, you have to scan down through effective 
>>each statement attempting to find the case in which you are interested. 
>>  Some cases can be compound.  The nested ifs can get confused with the 
>>surrounding ones (in Python or a language with explicit block 
>>delimiters).  The cases are often not written in any particular order, 
>>or they are ordered *for* performance reasons, but in ways that make it 
>>harder to "scan".
> 
> The problem I do see is your apples and oranges argument.  You are equating 
> at the extreme, "compound" if conditions with "_simple_" case statement 
> conditionals.  Yet you are leaving out of your argument the transition from 
> the former to the latter.  If mapping one to the other is simple then the 
> readability is no harder with if statements.  

I dispute that, and believe you've misunderstood my core point.  It's 
not anything to do with "equivalence" between the two approaches.  It's 
that if you see a set of if/else statements, you have to look at all of 
them to understand completely what's happening.  (I mean the structure 
of the if/else... the conditionals, not the contents of the blocks.) 
With a case statement, on the other hand, you *know* that it must be 
just simple conditionals (a series of x == some_constant tests), so you 
don't need to look at all the cases, just the one that interests you.

So it's not a comparison between two ways of writing the same thing, 
it's about the fact that with a case statement there are many things you 
*cannot* write, so reading one is much easier than reading a similarly 
sized compound if/else.

This is much like saying that a short function is easier to read than a 
long one.  The long one can obviously do much more, so it's an apples 
and oranges comparison in that sense.  But clearly if the short one fits 
all on one screen and the long one does not, the short one is basically 
much easier to grok.

That's all I'm saying.

> In my experience I've also seen where case statements promote overly long and 
> partially repetitive code blocks, which would be better constructed in a 
> top-down fashion.  Admittedly, if statements could be used in a similar way 
> but I've not seen the same level of abuse with such.  

That's true.

> So arguably, if the translation is pretty much one to one then the argument 
> is mute :~)  
      ^^^^ "moot"

Sort of, except my point here would be that a case statement is then the 
better choice in many cases because it communicates to the reader that 
the entire thing *is* simple, while the if/else/if/else does not.

-Peter



More information about the Python-list mailing list