Multiple return statements, readability

Possible duplicate:
If a function has only one return statement?

My teacher took off his glasses on some kind of Java code that I wrote (I still get A, this is only the first, not 100% class that I received in the java course). I will not argue with the teacher, but I would like to receive recommendations from real programmers. Here is the code snippet:

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, it is much clearer that initializing the return value, assigning in the case (and adding break; each line), returns the value. Of course, in the code that other people see, my opinion is not very powerful, so I would like to know that you guys think of several return statements in java (or C / C ++, for that matter), if you use multiple return statements you use it more than "if (this) return a; else return b;" expression? If you do not 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 degree of my practice of multiple reverse coding)

+7
source share
1 answer

Some scientists believe that there should be only one return statement at the end of a function. They believe that the multiple return statement makes the code somehow unclean.

However, most language developers and professional programmers disagree with this purist view. Multiple return statements can be confusing if your method is long and complex (but if so, you have more problems than multiple return statements). But often, multiple return statements can make the code more readable.

Your code is fine except for one change I would make: use default .

 switch(val) { case 0: return 's'; case 1: return 'c'; case 2: return 'h'; case 3: return 'd'; default: return 'h'; } 
+11
source

All Articles