Why do we need break after case statements?

后端 未结 17 2249
猫巷女王i
猫巷女王i 2020-11-22 04:34

Why doesn\'t the compiler automatically put break statements after each code block in the switch? Is it for historical reasons? When would you want multiple code blocks to e

17条回答
  •  北荒
    北荒 (楼主)
    2020-11-22 04:46

    As people said before, it is to allow fall-through and it is not a mistake, it is a feature. If too many break statements annoy you, you can easily get rid of them by using return statements instead. This is actually a good practice, because your methods should be as small as possible (for the sake of readability and maintainability), so a switch statement is already big enough for a method, hence, a good method should not contain anything else, this is an example:

    public class SwitchTester{
        private static final Log log = LogFactory.getLog(SwitchTester.class);
        public static void main(String[] args){
            log.info(monthsOfTheSeason(Season.WINTER));
            log.info(monthsOfTheSeason(Season.SPRING));
            log.info(monthsOfTheSeason(Season.SUMMER));
            log.info(monthsOfTheSeason(Season.AUTUMN));
        }
    
        enum Season{WINTER, SPRING, SUMMER, AUTUMN};
    
        static String monthsOfTheSeason(Season season){
            switch(season){
                case WINTER:
                    return "Dec, Jan, Feb";
                case SPRING:
                    return "Mar, Apr, May";
                case SUMMER:
                    return "Jun, Jul, Aug";
                case AUTUMN:
                    return "Sep, Oct, Nov";
                default:
                    //actually a NullPointerException will be thrown before reaching this
                    throw new IllegalArgumentException("Season must not be null");
            }        
        }
    }   
    

    The execution prints:

    12:37:25.760 [main] INFO lang.SwitchTester - Dec, Jan, Feb
    12:37:25.762 [main] INFO lang.SwitchTester - Mar, Apr, May
    12:37:25.762 [main] INFO lang.SwitchTester - Jun, Jul, Aug
    12:37:25.762 [main] INFO lang.SwitchTester - Sep, Oct, Nov
    

    as expected.

提交回复
热议问题