Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best Practices: Returning from method in case block of switch statement?

Tags:

c#

.net

Which method of returning a bool from a switch statement is preferable? I understand this may be subjective, however I feel it is important to our profession to get input on best practices :).

public bool foo(param)
{
    switch (param)
    {
        case 1:
            if (something)
            {
                return true;
            }

            return false;    
        default:
            return false;
     }
}

- OR -

public bool foo(param)
{
    bool flag = false;

    switch (param)
    {
        case 1:
            if (something)
            {
                flag = true;
            }
            break;
        default:
            break;
     }

    return flag;
}
like image 524
Polaris878 Avatar asked Aug 27 '10 21:08

Polaris878


1 Answers

The difference here is between single point of return and multiple points of return.

Generally, single point of return code tends to do a lot of bookkeeping (temporary variables, checking of those variables in loops), and can get hairy as the logic gets more complex. I've seen code that goes to great lengths to use a while (flag) ... flag = false; pattern instead of a while (true) ... break; pattern, and it is not fun to read.

I prefer multiple points of return since they return as early as possible (no extra work done) and don't require any locals to help keep track of the current return value. Also, I don't find them any harder to read than single point of return code.

There's a good disucssion of this on c2 (SingleFunctionExitPoint).

I've found that keeping methods as "functional" as possible is a good thing (I say "functional" here because I'm typically doing C# which, outside of LINQ, is not considered functional). By "functional", I mean that I try to avoid mutating state as much as possible. Introducing more state in the form of locals or members makes things more difficult to understand since you now have to take into consideration their values and you have to consider how those variables can be set (from another method, from another class, ...).

In general, state is evil, but sometimes it's a necessary evil.

This particular issue has some interesting conversation here on SO as well.

like image 51
Chris Schmich Avatar answered Sep 28 '22 21:09

Chris Schmich