Short conditions in IFs


Link to this posting

Postby Ursego » 21 Feb 2013, 21:56

Don't write complicated expressions in if statements. Instead, evaluate the expression in advance, store its result in a Boolean variable with a quality, descriptive name, and use that variable in the if statement.

That will make the logic being implemented extremely easy to understand!

*** BAD code: ***

Code: Select all
if ((calcMethod == CalcMethods.ADDITIVE && additiveCalculationPassed) || (calcMethod == CalcMethods.RATIO && ratioCalculationPassed))...


*** GOOD code: ***

Code: Select all
boolean structuralChangeOccurred;

structuralChangeOccurred =
      (calcMethod == CalcMethods.ADDITIVE && additiveCalculationPassed) ||
      (calcMethod == CalcMethods.RATIO && ratioCalculationPassed);
       
if (structuralChangeOccurred)...

The bad code tells us only WHEN the condition is true, but the good code tells us both WHEN and WHY!!!

The expression in my example is very primitive because it's enough to convey the idea. In the real life, I have seen statements with half-a-screen Boolean expressions inside an if!

When the logic is complicated, don't populate the Boolean variable in one assignment statement (as described above). Instead, come to the truth step by step, using a number of simple Boolean expressions rather than one monstrous construction:

*** BAD code: ***

Code: Select all
boolean theShowMustGoOn;

theShowMustGoOn = ([cond1] || [cond2]) || ([cond3] && [cond4] && this.isXxx()) || ([cond3] && this.isYyy());

if (theShowMustGoOn)...

*** GOOD code: ***

Code: Select all
boolean theShowMustGoOn;

if ([cond1] || [cond2])
   theShowMustGoOn = true;
elseif ([cond3] && [cond4])
   theShowMustGoOn = this.isXxx();
elseif ([cond3])
   theShowMustGoOn = this.isYyy();
else
   theShowMustGoOn = false;

if (theShowMustGoOn)...

It's not only more readable. It also simplifies debugging and, potentially, improves performance: the functions (which can be not very efficient if they call a web service or contain a heavy database query) have a chance not to be called at all (if a previous validation has already produced true).
User avatar
Ursego
Site Admin
 
Posts: 124
Joined: 19 Feb 2013, 20:33



IF you want to ((lose weight) OR (have unbelievable (brain function AND mental clarity))) THEN click:




cron
free counters

eXTReMe Tracker