http://www.perlmonks.org?node_id=136122


in reply to Why I Hate Nested If-Else blocks

Take a look at my CSV Database Validation program. I use a few nested If-Else-If blocks and I consider them to be very useful. If the next if's are logically dependant on one another, they are a Good Thing. As for the example you provide, I think you could have done better (sorry!). Most (not all) usage of the ref function is due to poor design on the part of the programmer and examining the code can give ideas on how to redesign to avoid that. Ignoring that for a moment, let's look at this code:

if ( $foo > 7 ) { if ( $bar ) { bar_func( $foo ); } elsif ( $baz ) { baz_func( $foo ); } }

The two subroutines are dependant on $foo evaluating as true. If I want to avoid nested ifs, I could do this:

if ( $foo > 7 and $bar ) { bar_func( $foo ); } elsif ( $foo > 7 and $baz ) { baz_func( $foo ); }

Frankly, while that works, it's poor programming style. You have duplicate code and that's not a good thing. If the two functions are logically dependant on $foo's value, they should be grouped so that you only test the value once. If those sections of code are far apart, it's easy to miss updating one of the tests, if the condition needs to change. Sure, I could create dispatch tables or jump through all sorts of hoops to get around this, but nested if statements can add clarity to code (unless you're nesting eight levels deep).

Cheers,
Ovid

Join the Perlmonks Setiathome Group or just click on the the link and check out our stats.