Single-exit functions

Ivan Moore suggests that single-exit functions should be considered cargo cult. I don’t think so. My suggestion for improving his sample code is as follows:

void foo(boolean condition)
{
    int returnValue = 6;
    if (condition)
        returnValue = 5;
    return returnValue;
}

Single exit. I even managed to save on a rather confusing else. Short. Easy to read. Even easier to understand.

Anyway, as long as we’re dealing with code of the complexity like the function shown, it doesn’t really matter if you use the single-exit rule or not (As long as you don’t work in my team :-). Single-exit becomes important if your function gets longer & more complex. However, if your function gets substantially longer and substantially more complex, you should consider refactoring it anyway.

Comments are closed.