# Short conditions in IFs

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!

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

*** GOOD code: ***

Code: Select all
boolean structuralChangeOccurred;

structuralChangeOccurred =
(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:

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).

Ursego