More on Single-exit functions

Ivan Moore posed the question what happens to the solution I suggested if the function returns the result of some other function:

void foo(boolean condition)
{
    int returnValue = calculateSomeValue();
    if (condition)
        returnValue = calculateSomeOtherValue();
    return returnValue;
}

Two considerations:

First, if calculateSomeValue() is O(1) or even O(n), I would still use the proposed single-exit/no-else variation. Truth to be told, I don’t even care if calculateSomeValue() is O(n*n) – I would go for the simple solution anyway. If, and only if, performance analysis shows that foo() is a system bottleneck, I would change it.

Second, if calculateSomeValue() has some undesired side-effects and thus should only be called if condition is indeed true. What’s “undesired side-effect” in this context? If the undesired side-effect is performance / resource-related (e.g. calculateSomeValue() goes out to fetch some data from a database or from a web-service), then it’s just a variation of the O(1)/O(n)/O(n*n) discussion above. I would still go for my single-exit approach and worry about performance later. On the other hand, if “undesired side-effect” means calculateSomeValue() does some changes to the systems state in addition to, well, calculating some value, then my suggestion is to check if this wouldn’t be great opportunity to improve the design & implementation of calculateSomeValue(). If that’s not possible, e.g. when working in a legacy-code environment, then I would go for the two-exits approach.

Comments are closed.