Switch statement with returns — code correctness

前端 未结 17 2175
梦如初夏
梦如初夏 2020-12-12 20:05

Let\'s say I have code in C with approximately this structure:

switch (something)
{
    case 0:
      return \"blah\";
      break;

    case 1:
    case 4:
         


        
17条回答
  •  离开以前
    2020-12-12 20:53

    If you have "lookup" type of code, you could package the switch-case clause in a method by itself.

    I have a few of these in a "hobby" system I'm developing for fun:

    private int basePerCapitaIncomeRaw(int tl) {
        switch (tl) {
            case 0:     return 7500;
            case 1:     return 7800;
            case 2:     return 8100;
            case 3:     return 8400;
            case 4:     return 9600;
            case 5:     return 13000;
            case 6:     return 19000;
            case 7:     return 25000;
            case 8:     return 31000;
            case 9:     return 43000;
            case 10:    return 67000;
            case 11:    return 97000;
            default:    return 130000;
        }
    }
    

    (Yep. That's GURPS space...)

    I agree with others that you should in most cases avoid more than one return in a method, and I do recognize that this one might have been better implemented as an array or something else. I just found switch-case-return to be a pretty easy match to a lookup table with a 1-1 correlation between input and output, like the above thing (role-playing games are full of them, I am sure they exist in other "businesses" as well) :D

    On the other hand, if the case-clause is more complex, or something happens after the switch-statement, I wouldn't recommend using return in it, but rather set a variable in the switch, end it with a break, and return the value of the variable in the end.

    (On the ... third? hand... you can always refactor a switch into its own method... I doubt it will have an effect on performance, and it wouldn't surprise me if modern compilers could even recognize it as something that could be inlined...)

提交回复
热议问题