The wrong solution to deep nesting

Posted by admin, Wed Aug 23 05:49:15 UTC 2006


Krzysztof Kowalczyk weblog

The way to avoid deeply nesting is to do early exit as soon as possible. The trivial example could be rewritten as:
<br />if (!foo) return;      <br />if (!bar) return;      <br />if (!anotherVariable) return;      <br />… and this is the logic<br />



I violently disagree with this solution to the unreadability of deeply nested if’s. IMO, you are just trading one problem (poor readability) for another problem (really hard to debug). If you have deeply nested if’s, then you probably need to apply the state machine design pattern to your code.

Filed Under: | Tags:

Comments

Have your say

A name is required. You may use HTML in your comments.