do this without using an “if” | if(s == “value1”){…} else if(s == “value2”) { …}

前端 未结 18 2156
温柔的废话
温柔的废话 2021-01-30 09:36

According to anti-if campaign it is a best practice not to use ifs in our code. Can anyone tell me if it possible to get rid of the if in this piece of code ? (switch is also

18条回答
  •  时光取名叫无心
    2021-01-30 10:05

    First of all, be very attentive when reading such "anti" campaigns.

    • Ask yourself if Anti IF campaign would like eliminate the logic in the applications?!
    • The ideas could have a good application in one situation and a stupid in another one. Be reasonable.
    • It may be possible that multiple usage of IF may encumber the reader of the code. but this is any reason to eliminate the if from your code, more that than, this is almost impossible.
    • By the way anywhere in the MS design guidelines is indicated do not use if (like is done, by e.g. for the goto statement usage of which is not recommended)...

    C#

        switch (myStringVar)
        {
            case "one": doSomething();  break;
            case "two": doSomething(); break;
            case "three": doSomething(); break;
            default: doSomething(); break;
        }
    

    Finally, it reduces this code to the if s... so, only for readability is better, not for performance.

    Actually, if Microsoft believes that switch (in c#) is better to replace with if's - OK, I will use (in the concrete situation that you described) the switch.

    By the way, it seems that the campaign responds to your question very clear in this example

提交回复
热议问题