Monday, 30 September 2013

Using nested if statements to structure code

Using nested if statements to structure code

I'm trying to structure my code in a readable way. I've read that one way
of doing it is as follows:
if(Init1() == TRUE)
{
if(Init2() == TRUE)
{
if(Init3() == TRUE)
{
...
Free3();
}
Free2();
}
Free(1);
}
I like this way of doing things, because it keeps each FreeX inside its
matching InitX loop, but if the nesting goes beyond three levels it
quickly becomes unreadable and goes way beyond 80 columns. Many functions
can be broken up into multiple functions so that this doesn't happen, but
it seems dumb to break up a function just to avoid too many levels of
nesting. In particular, consider a function that does the initialization
for a whole class, where that initialization requires ten or more function
calls. That's ten or more levels of nesting.
I'm sure I'm overthinking this, but is there something fundamental I'm
missing in the above? Can deep nesting be done in a readable way? Or else
restructured somehow whilst keeping each FreeX inside its own InitX loop?
By the way, I realise that the above code can be compacted to if(Init1()
&& Init2()..., but the code is just an example. There would be other code
between each InitX call that would prevent such a compaction.

No comments:

Post a Comment