What’s the difference between Return and break in a switch case?

Asked

Viewed 6,900 times

10

In some situations it is necessary to practice the switch case for optimization and improvement of code. I have an application developed for Android using Java, which in case is used of both situations. Below I have an example using return in which it is used with Tabs:

switch (position){
    case 0:
        Tab tab1 = new Tab1();
        return tab1;
    case 1:
        Tab tab2 = new Tab2();
        return  tab2;
    case 2:
        Tab tab3 = new Tab3();
        return tab3;
}

In this case below we have to use the break in which the desired month is defined:

    int month = 8;
    String monthString;
    switch (month) {
        case 1:  monthString = "January";
                 break;
        case 2:  monthString = "February";
                 break;
        case 3:  monthString = "March";
                 break;
        case 4:  monthString = "April";
                 break;
        case 5:  monthString = "May";
                 break;
        case 6:  monthString = "June";
                 break;
        case 7:  monthString = "July";
                 break;
        case 8:  monthString = "August";
                 break;
        case 9:  monthString = "September";
                 break;
        case 10: monthString = "October";
                 break;
        case 11: monthString = "November";
                 break;
        case 12: monthString = "December";
                 break;
        default: monthString = "Invalid month";
                 break;
    }

In the SO gringo, there’s an explanation, but I don’t understand exactly what diverges one from the other. What is the real difference between return and the break in a switch case?

  • 2

    The break only breaks the switch flow, that is, it interrupts the continuity from the block. Return breaks the flow of the method to which it is part.

  • Recalling that the switch is one of the most horrific language constructions in Java. It has been inherited from C and C++, and has been a horrific thing since it was born in C. Avoid using it, only use it if you really.

  • 1

    @Victorstafusa good, but maybe, I say maybe, is better than using a "ifelse" sausage. By chance there is some other alternative?!

  • 1

    @Acklay, yes there is. In the first case you can do (with Java 8) Supplier<Tab1> a = Tab1::new; Supplier<Tab2> b = Tab2::new; Supplier<Tab3> c = Tab3::new; return Arrays.asList(a, b, c).get(position).get();. In your second case you can use String[] meses = {"Invalid month", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"}; String monthString = meses[month < 1 || month > 12 ? 0 : month];

  • @Victorstafusa cool. I’ll do a deep search on that side. But this option not to use switch is a performance issue or just a matter of opinion?

  • 2

    @Acklay is a matter of readability and maintainability of code. The switch is sometimes compared to the goto. A code using goto works and performs well, but the code quickly tends to become a disorganized, gambiarrado spaghetti - the same goes for the switch, only in a degree not so bad, but still bad. What happens is that almost always there is some alternative better using something else. In the case of switch, polymorphism is the most frequent output, but there are others (such as the ones I used above, based on arrays).

  • @Victorstafusa + 1 by comment. It was quite useful and clarified enough. Abs.

  • 3

    Switch is one of the cleanest ways to do things like state machines and any other conditional jump situations with constant values, and in languages like C is much more performatic than various other structures because of the jump tables. Programming well has a lot to do with knowing the specialized tools and knowing how to use, and not just with using tools that are cute, colorful and with rubberized cables. As for the implementation, I would not know how to say in Java to the point of saying whether it is good or not. In C I would say that is a powerful ally.

  • 1

    In other words, the switch in C and some other languages is not a syntax sugar, It is a specialized and powerful tool for what has been designed. In no way can it be compared with if, elseif and similar, except for the "impression" that it passes from functionality. The reason it exists is different, the internal functioning is completely different. To understand the reason of the break, you have to understand that there is only one block, which is the switch whole, and not just case. In PHP, for example, this is all lost. So yes it’s really just "one more way to do if".

  • @Bacco The same can be said of goto - There are situations where it is the best tool. However, most of the time, those who use it end up doing lambança even. I agree that state machines and jumps based on numerical values, the switch has the best performance, but even so it is rather likely to be used incorrectly, especially in cases where polymorphism would be the alternative. In Java, the switch exists at bytecode level and hotspot will probably compile this with JIT in something similar to C in cases where performance makes a difference.

  • @Victorstafusa yes, in C o switch is a super goto in the sense of functionality, but less "dangerous" because the destination is contained in the block of the switch. I think it’s important that people understand what he is, because his bad reputation is usually due to misuse (which is due to the lack of clarity when teaching).

  • 1

    @Bacco Well, maybe I didn’t get the tone of my words right at the beginning. The idea isn’t to simply abolish the switch and never use it, but evaluate that normally it is not the best solution. On the other hand it also means that from time to time, in some more specific cases, it is rather the best answer. My alert is more because there are a lot of people who fall in love when you meet him and start punching switch the left and right to do everything because it is quite versatile and flexible - as well as the goto is also.

  • 2

    @Victorstafusa yes, put this way I agree. For me the important point is that (at least in C) people understand that it is a unique tool, and with a specialized behavior (and a block only, so the eventual use of break where applicable). Not a simple alternative to other structures. And as such, should not be abused, really.

Show 8 more comments

3 answers

21


The return ends the execution of the method regardless of where it is and returns the value.

The break force (manually) the output of a loop or conditional in case the switch.

In the second code if there is something else to be executed later switch will be executed if it were a return as in the first example the method would end right there.

The example below shows that in that context the use of break and return is exactly the same, once made the choice the method ends no other action happens.

As for the use of the most suitable for the situation some important points to think about are:

  • I need to return value?

  • After the choice has been made (on parole) some more action must take place?

  • When choosing the Return I must use the single return technique (SESE)?

Recommended reading:

Why should I only use a "Return" in each function?

Example - ideone


class Ideone
{
    public static void main (String[] args) throws java.lang.Exception
    {
        System.out.println("Com Break: "+ comBreak(1));
        System.out.println("Com Return: "+ comReturn(1));
    }

    public static String comBreak(int mes){
        String mesExtenso = "";
        switch (mes){
            case 1: 
                mesExtenso = "Janeiro";
                break;
            case 2: 
                mesExtenso = "Fevereiro";
                break;              
            case 3: 
                mesExtenso = "Março";
                break;              
            default: 
                mesExtenso = "Mês inválido";
                break;              
        }
        System.out.println("Instruções executadas antes do return");
        return mesExtenso;
    }


    public static String comReturn(int mes){

        switch (mes){
            case 1: 
                return "Janeiro";
            case 2: 
                return "Fevereiro";
            case 3: 
                return "Março";
            default: 
                return "Mês inválido";
        }
        //Qualquer instrução daqui para baixo gera o erro "unreachable statement"
        //return "Forever alone :( ....";

    }   

}
  • Just to add that the break is most often seen as a sledgehammer, not a good programming practice. To learn more, I suggest the topic http://softwareengineering.stackexchange.com/questions/58237/are-break-and-continue-bad-programming-practices

  • 1

    @leonardopessoa has some related issues (in English) Why the use of "break" is considered bad? and One should break into a?

  • @Leonardopessoa the issue you linked deals with flow changes in different situations to switch, in repeat situations. The case of switch is perfectly applicable and out of context for repetition flow control like that of the question in SESE

10

The break, only closes the execution of switch and goes to the next instruction after it, it is essentially the same that occurs in a loop. The return doesn’t do anything special inside the switch, it closes the execution of the function where that code is.

It was unfortunate that break be the same output command as a loop. But it is mandatory and the default is used in almost all situations of the switch.

The answer accepted in the OR is confused and almost wrong.

3

Sorry to diverge from the 'almost wrong''.

The answer in the OS says that the RETURN immediately returns to the point from which it was called while the break just exits the loop without returning - ie the function could continue doing other things before returning.

Which, in my opinion, is correct.

  • 3

    The way it is written is confusing, and depending on how to interpret it, it gives room for it, is wrong, as it can also be interpreted differently and then it would be correct, I said almost wrong. She has negatives and fewer votes than other answers probably because of this.

  • 3

    "The almost wrong" is to call a switch block "loop" - it is a flow control construct, but is only called "loop" (loop) if it is a construction that allows repetition of the block - as while, for etc...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.