Question

Possible Duplicate:
Should a function have only one return statement?

My teacher took points off on some java code I wrote (I'm still getting an A, this is just the first non 100% grade I've gotten in the java course) I'm not going to argue with the teacher on the point, but I would like to get some advice from actual programmers. Here is the offending piece of code:

private char byte2suit(byte val) {
    switch(val) {
        case 0: return 's';
        case 1: return 'c';
        case 2: return 'h';
        case 3: return 'd';
        }
    //fallback value
    return 'h';
    }

In my opinion this is much clearer that initalizing a return value, assigning in the case (and adding break; every line) then returning the value. Of course, in code other people see, my opinion isn't all powerful, so I would like to know what you guys think about multiple return statements in java (or C/C++ for that matter), if you do use multiple return statements do you use it more than the "if (this) return a; else return b;" statement? If you don't use multiple return statements, can you give a really convincing reason ( unreadable code is not a reason if the above code IS readable and is the maximum extent of my multiple return coding practice )

Was it helpful?

Solution

Some academics believe that there should only be one return statement at the end of the function. They believe that multiple return statement make the code impure in some way.

However most language designers and professonal programmers disagree with this purist view. Multiple return statements can be confusing if your method is long and complicated (but if this is the case, you have bigger problems then multiple return statements). But often multiple return statements can make the code more readable.

Your code is fine, apart from one change I'd make: use default.

switch(val) {
    case 0: return 's';
    case 1: return 'c';
    case 2: return 'h';
    case 3: return 'd';
    default: return 'h';
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top