Using two values for one switch case statement

前端 未结 12 1778
梦谈多话
梦谈多话 2020-11-28 17:56

In my code, the program does something depending on the text entered by the user. My code looks like:

switch (name) {
        case text1: {
            //bla         


        
12条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-28 18:33

    The fallthrough answers by others are good ones.

    However another approach would be extract methods out of the contents of your case statements and then just call the appropriate method from each case.

    In the example below, both case 'text1' and case 'text4' behave the same:

    switch (name) {
            case text1: {
                method1();
                break;
            }
            case text2: {
                method2();
                break;
            }
            case text3: {
                method3();
                break;
            }
            case text4: {
                method1();
                break;
            }
    

    I personally find this style of writing case statements more maintainable and slightly more readable, especially when the methods you call have good descriptive names.

提交回复
热议问题