note
mstone
<p>
<br>&gt; Yes, there are times when there are much more elegant solutions
<br>&gt; then nested if-elses, but shouldn't the goal be simplicity over
<br>&gt; a blanket condemnation? I guess I'm just not seeing the why in
<br>&gt; "Why I Hate Nested If-Else blocks."
</p>
<p>
A series of nested conditionals forms a state machine. Every block is its own state, and every test marks a transition from one state to the next:
</p>
<code>
if ($a) {
if ($b) {
&S1;
} else {
&S2;
}
} else {
if ($c) {
&S3;
} else {
&S4;
}
}
</code>
is equivalent to:
<code>
+-----(b)->[S1]--+
| |
+-----(a)->[test b]--+ |--+
| | | |
| +-(not-b)->[S2]--+ |
[test a]--| |-->[end]
| +-----(c)->[S3]--+ |
| | | |
+-(not-a)->[test c]--+ |--+
| |
+-(not-c)->[S4]--+
</code>
<p>
Nested conditionals work well if the machine you're building graphs out to a simply-connected binary tree, like the one above, but they become less desirable as your machine grows more complex.
</p>
<p>
Basically, the problem boils down to representing arbitrary data structures with a binary tree. There are some things you just can't do directly, like forming complex connections:
</p>
<code>
+-----(b)->[S1]-+
| |
+-----(a)->[test b]-+ +---->[S5]-+
| | | |
| +-(not-b)->[S2]---+ |
[test a]-+ | | +->[end]
| | | |
| +-----(c)->[S3]-+ | |
| | +-->[S6]-+
+-(not-a)->[test c]-+ |
| |
+-(not-c)->[S4]---+
</code>
<p>
So you have to simulate the connections by duplicating nodes:
</p>
<code>
+-----(b)->[S1]->[S5]-+
| |
+-----(a)->[test b]--+ |--+
| | | |
| +-(not-b)->[S2]->[S6]-+ |
[test a]--| |-->[end]
| +-----(c)->[S3]->[S5]-+ |
| | | |
+-(not-a)->[test c]--+ |--+
| |
+-(not-c)->[S4]->[S6]-+
</code>
<p>
Which introduces synchronization problems.
</p>
<p>
The more complicated your machine is, the harder you have to twist it around to fit the binary-tree model of nested conditionals. And the more you twist, the harder it is to figure out what the original machine looked like while you're reading the code.
In fact, since programmers often evolve code instead of designing it, I'd give strong odds that even the programmer who writes a series of nested conditionals doesn't know what kind of machine he's building, and can't prove that it's a well-formed minimal solution to the problem at hand.
</p>
<p>
So it's not that nested conditionals are inherently evil. They're quite useful when applied properly. So are gotos. And like gotos, nested conditionals give programmers a way to disguise sloppy or inconsistent thinking as complex control flow. In other words, they can make code unnecessarily complex while looking perfectly reasonable every step of the way. That's why we should use them carefully and examine them critically, not just accept them blindly.
</p>
136097
136301