Re: Control Flow Coding Style
Dimitris Andreou <[email protected]>
| Newsgroups | gmane.comp.programming.language-of-the-year |
|---|---|
| Message-ID | <[email protected]> |
O/H Avdi Grimm έγραψε:
> > 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.
If the else part is never supposed to execute, why write an "if"
statement then?
The following blocks are semantically equal, but I consider the latter
as clearer:
if (assumption) {
//block A
} else {
throw new AssertionError();
}
<=>
assert assumption;
//block A
or:
if (!assumption) throw new AssertionError("something is very wrong");
//block A
This style ties together the assertion and the associated error, and
these should be close together. It removes an unnecessary nesting over a
block of code, and make it easier for a human to spot what the assertion
is (because in the first style, only when the reader gets to the "else"
part he understands that the condition of the "if" clause was really an
assertion, and not an expected case out of many).