Oftentimes one has code that uses the same values in multiple branches of an if statement. DRY would dictate that those values are only instantiated in the code once. Example code:
func f() {
let x1 = resultOfExpensiveComputationWithNoSideEffects1()
let x2 = resultOfExpensiveComputationWithNoSideEffects2()
if cond1 && cond2 {
// use x1 and x2
} else if cond1 {
// use x1
} else if cond2 {
// use x2
} else {
// use neither
}
// x1 and x2 are not used after this point
}
While the initialization of x1
and x2
before the if
block makes for cleaner code, x1
and x2
will be created regardless of whether they are actually needed, which means that the expensive computations may be performed needlessly. The alternative would be to write out let x1 = resultOfExpensiveComputationWithNoSideEffects1()
inside each branch that x1
is used (and likewise for x2
), but this violates DRY. There is no way to rearrange the if
block to write the initialization of each of those variables only once.
Proposal: If x1
and x2
could be declared as lazy var
(or even lazy let
, as the restrictions of init
no longer apply), then the expensive computations would only be performed if the branches of the if
block requiring them were actually taken.