by Ursego » 21 Feb 2013, 21:56
Don't write complicated expressions inside of if statements (just after the if); instead, store the expression's 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: ***
PB:
- Code: Select all
if (ls_calc_method = n_calc_method.ADDITIVE and lb_additive_calculation_passed) or (ls_calc_method = n_calc_method.RATIO and lb_ratio_calculation_passed) then...
Java:
- Code: Select all
if ((calcMethod == CalcMethods.ADDITIVE && additiveCalculationPassed) || (calcMethod == CalcMethods.RATIO && ratioCalculationPassed))...
*** GOOD code: ***
PB:
- Code: Select all
lb_structural_change_occurred = &
(ls_calc_method = n_calc_method.ADDITIVE and lb_additive_calculation_passed) or &
(ls_calc_method = n_calc_method.RATIO and lb_ratio_calculation_passed)
if lb_structural_change_occurred then...
Java:
- Code: Select all
boolean structuralChangeOccurred;
structuralChangeOccurred =
(calcMethod == CalcMethods.ADDITIVE && additiveCalculationPassed) ||
(calcMethod == CalcMethods.RATIO && ratioCalculationPassed);
if (structuralChangeOccurred)...
As you see, the bad code tells us only WHEN the condition is true, but the good code tells us both WHEN and WHY!!! It is so important that I easily go against the rule to decrease scripts size - I don't try to keep my scripts short in any price, sometimes I prefer to ADD LINES if that makes the code more understandable and not looking like a heap of rubbish. And, of course, don't forget that the expression in my example is pretty small 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! If the logic is complicated then don't populate the Boolean variable in one assignment statement (as described above) but come to the truth step by step, using a number of simple Boolean expressions instead of one monstrous construction. Please see the next example of populating a variable step by step instead of inserting everything in the if statement:
PB:
- Code: Select all
boolean lb_the_show_must_go_on
lb_the_show_must_go_on = false
choose case true
case [cond1], [cond2]
lb_the_show_must_go_on = true
case [cond3] and [cond4]
lb_the_show_must_go_on = this.uf_xxx()
case [cond3]
lb_the_show_must_go_on = this.uf_yyy()
end choose
if lb_the_show_must_go_on then...
Java:
- Code: Select all
boolean theShowMustGoOn;
theShowMustGoOn = false;
if ([cond1]||[cond2])
theShowMustGoOn = true;
elseif ([cond3]&&[cond4])
theShowMustGoOn = this.isXxx();
elseif ([cond3])
theShowMustGoOn = this.isYyy();
if (theShowMustGoOn)...