Reputation: 1967
what's a better way to do things?
if f1() and f2() then...
or
if f1() then
if f2() then
or:
fBoolean1 := f1()
fBoolean2 := f2()
if fboolean1 and fboolean2 then...
In the first example I'm not sure which of the two functions gets evaluated. In the second example f2 only gets evaluated if f1 evaluates true and in the third example both f1 and f2 get evaluated.
What's the best way to do this?
Upvotes: 3
Views: 200
Reputation: 108963
The compiler is smart. In your first sample, if f1
returns false
, then f2
will not even be called (unless you change the default compiler settings by disabling lazy evaluation or boolean short-circuit evaluation). Hence, the first option is equivalent to the second one (again, unless you have changed the default settings).
Consequently, perfomance-wise, the two first options are better. Otherwise, it is a matter of taste. The second option will yield two blocks of code, with two levels of code indentation (if you follow the standard rules of indentation, as you seem to do). Perhaps you'd prefer the first option for this reason.
Of course, if you need to use the value returned by f1
and f2
later, perhaps several times, the third option is superior.
Upvotes: 8