Why do we need break after case statements?

后端 未结 17 2051
猫巷女王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:40

    You can do all sorts of interesting things with case fall-through.

    For example, lets say you want to do a particular action for all cases, but in a certain case you want to do that action plus something else. Using a switch statement with fall-through would make it quite easy.

    switch (someValue)
    {
        case extendedActionValue:
            // do extended action here, falls through to normal action
        case normalActionValue:
        case otherNormalActionValue:
            // do normal action here
            break;
    }
    

    Of course, it is easy to forget the break statement at the end of a case and cause unexpected behavior. Good compilers will warn you when you omit the break statement.

    0 讨论(0)
  • 2020-11-22 04:41

    So you do not have to repeat code if you need several cases to do the same thing:

    case THIS:
    case THAT:
    {
        code;
        break;
    }
    

    Or you can do things like :

    case THIS:
    {
       do this;
    }
    case THAT:
    {
       do that;
    }
    

    In a cascade fashion.

    Really bug/confusion prone, if you ask me.

    0 讨论(0)
  • 2020-11-22 04:42

    Exactly, because with some clever placement you can execute blocks in cascade.

    0 讨论(0)
  • 2020-11-22 04:46

    I think it is a mistake. As a language construct it is just as easy to have break as the default and instead have a fallthrough keyword. Most of the code I have written and read has a break after every case.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-22 04:46

    You can makes easily to separate other type of number, month, count.
    This is better then if in this case;

    public static void spanishNumbers(String span){
    
        span = span.toLowerCase().replace(" ", "");
        switch (span){
         case "1":    
         case "jan":  System.out.println("uno"); break;    
         case "2":      
         case "feb":  System.out.println("dos"); break;    
         case "3":     
         case "mar":  System.out.println("tres"); break;   
         case "4":   
         case "apr":  System.out.println("cuatro"); break;
         case "5":    
         case "may":  System.out.println("cinco"); break;
         case "6":     
         case "jun":  System.out.println("seis"); break;
         case "7":    
         case "jul":  System.out.println("seite"); break;
         case "8":    
         case "aug":  System.out.println("ocho"); break;
         case "9":   
         case "sep":  System.out.println("nueve"); break;
         case "10":    
         case "oct": System.out.println("diez"); break;
         }
     }
    
    0 讨论(0)
提交回复
热议问题