if statements with or w/o else statements

Dang Griffith noemail at noemail4u.com
Mon Feb 23 10:31:31 EST 2004


On Mon, 23 Feb 2004 08:03:40 -0600, Mark McEahern <mark at mceahern.com>
wrote:
>That is, e.g., you're testing for a pre-condition that, if false,
>indicates failure.  In that case, NOT having an else statement is likely
>to mask subtle bugs and it's probably better to have:
>
>if preCondition:
>  doSomething()
>else:
>  raise RuntimeError('X must be true.')
>
>which itself can be expressed differently so that you don't need the
>else, e.g.,
>
>if not preCondition:
>  raise RuntimeError(...)
>doSomething()
In general, I recommend avoiding "negative" test conditions like this.
However, I recommend them for testing preconditions at the start (or
as early as possible) of a method.  When there are multiple,
related/dependent preconditions, using positive tests can lead to
having the *useful* code nested in a confusing bunch of conditions.

Using a linear sequence of negative test conditions at the top makes
it more clear that it is indeed the preconditions being tested
(because the code exits/returns/raises when the condition is true),
rather than business logic.  Plus, the business logic is not
unnecessarily indented, which also help avoid long lines wrapping
(your editor and printer prefences may vary).
    --dang



More information about the Python-list mailing list