Download Growing Better Software

Transcript
143
The result of the last if statement is never overridden. Because
of this, we can move it up all the way to the start of the function.
The return statement we added helps us to preserve the
meaning of the code.
function return_a_value(bool mustreturnthird,
bool mustreturndefault)
{
// return the third value, default or a sum
if(mustreturndefault)
{
int defaultvalue = lookup_default();
resultvalue = defaultvalue;
return resultvalue;
}
int firstvalue = lookup_first();
int secondvalue = lookup_second();
int resultvalue = firstvalue+secondvalue;
}
if (mustreturnthird)
{
int thirdvalue=lookup_third_value();
resultvalue = thirdvalue;
}
return resultvalue;
Likewise, the last if statement overrides the result value
calculated before it (however, it will not override our first if
statement anymore due to the return statement). We can also
add a return statement to it, which once again leaves the
meaning of the last snippet of code intact: