Java switch cases: with or without braces?

51,929

Solution 1

is there any sort of performance penalty for using the braces with a case?

None.

The curly braces are there to help the compiler figure out the scope of a variable, condition, function declaration, etc. It doesn't affect the runtime performance once the code is compiled into an executable.

Solution 2

No performance penalty from an execution point of view.

Slight performance penalty from a compiling point of view as there is more to parse, but if anyone were actually that concerned about it they would have to write their code all on one line :-)

And now for the opinion part of our post... I always put in the { and } because there is a penalty for maintainability in that you will likely have to put them in at a later date, and it can be a pain putting them in later... but that is 103% personal preference.

Solution 3

As we know braces for switch cases are not necessary. Using braces cases may cause a confusion about the scope of a case.

An opening brace is generally associated with something meaningful like a start of a function or start of a loop or start of class declaration or start of array initialization etc...We know that, a case breaks out of switch block when it encounters a break statement. Thus using curly braces seems to imply idea of a different scope for case to an ignorant reader. So, its better to avoid using curly braces for the sake of better programming readability.

i.e. When I have something like,

switch(i)
{
  case 1 :
  {
     //do something
  }
  System.out.println("Hello from 1");

  case 2: 
  ....
}

"Hello from 1" gets printed. But use of curly brace may suggest an ignorant reader that the case ends with '}', already knowing what curly braces generally signify in case of loops, methods etc.

Like we have jump-to-label statements in 'C' the control just shifts to case and continues it's execution. So, with that understanding it's just a BAD practice to use curly braces when writing cases for switch.

Technically speaking you can surround any block of your code with an additional pair of curly braces when used with valid syntax. Using braces in switch looks so bad at least to me as it seems to give a different feel like I have said above.

My suggestion : Just avoid using surrounding braces for switch cases.

Solution 4

With braces.

There are so many things that can go wrong with switch statements I try to avoid them where I can, i.e.

  1. Forgetting breaks and thus having case fall-throughs
  2. Forgetting a default case and thus not catching an un-catered for condition
  3. Accidentally reusing variables between case statements, or worse yet, affecting a variable which IS sharing a variable between case statements.

Using braces is one way to prevent both intentional and accidental sharing of variables between case statements

Solution 5

You say the braces can be omitted because no variables names are being reused. By reusing variable names, I assume you mean declaring a new variable of the same type.

The braces are actually most useful to ensure you don't end up reusing the same variable in different cases by mistake. They don't declare any variables today, but someone will add them tomorrow and without the braces the code is error-prone.

Share:
51,929
cdmckay
Author by

cdmckay

CTO and Co-Founder at Process Street Open Source Programmer (https://github.com/cdmckay)

Updated on July 23, 2022

Comments

  • cdmckay
    cdmckay almost 2 years

    Consider the following two snippets, with braces:

    switch (var) {
      case FOO: {
        x = x + 1;
        break;
      }
    
      case BAR: {
        y = y + 1;
        break;
      }
    }
    

    Without braces:

    switch (var) {
      case FOO:
        x = x + 1;
        break;
    
      case BAR:
        y = y + 1;
        break;
    }
    

    I know that, in the snippet with braces, a new scope is created by enclosing each case in braces. However, if each case does not need the new scope (i.e. no variable names are being reused), is there any sort of performance penalty for using the braces with a case?

  • Andy White
    Andy White about 15 years
    I guess it's kind of an objective question... I retract the argumentative thing
  • cdmckay
    cdmckay about 15 years
    I prefer it without the braces... I find the braces add a lot of unneeded noise.
  • Andy White
    Andy White about 15 years
    Yeah, I wish it was more like this: case(FOO){x=x+1} case(BAR){y=y+1}
  • Shog9
    Shog9 about 15 years
    Sensible whitespace == nice. Unnecessary braces == suck.
  • Andy White
    Andy White about 15 years
    whitespace == mix of tabs and spaces == suck (just thought I'd throw a tab vs. space comment into the mix)
  • TofuBeer
    TofuBeer about 15 years
    the { and } make things stand out though as well, which makes it easier to read (IMO).
  • TofuBeer
    TofuBeer about 15 years
    yup. I was going to share a story of a method I once had to modify (took me about 4 hours to add one line of code) but the code was insane (about 10 pages long and 4 pages wide when printed) so it isn't the typical case. But if it had use {} then it would have taken a minute to add it.
  • Gareth Davis
    Gareth Davis about 15 years
    I think the point is here that if the original programmer had gone to the effort of putting in {} blocks so that the code was more readable they might have actually cared that they where writing a 10 page switch statement and changed the code to be a little less insane
  • nyaray
    nyaray almost 11 years
    I'm a bit curious since I can't see the answer myself... @TofuBeer, when do you HAVE to add the braces? Also, I totally agree with the maintainability point, I just don't see the maintainability issue ATM. EDIT: nevermind. I just read the rest of the answers below.
  • TofuBeer
    TofuBeer almost 11 years
    You do in C++ in some cases, so if you work in both languages it isn't a bad habit to get into either.
  • ataulm
    ataulm over 10 years
    Including points 1 and 2 was misleading for this question (for me); your closing line should explicitly say that braces solves 3 only - I thought you meant that braces precluded the need for breaks, then tried it.
  • dsingleton
    dsingleton almost 10 years
    Point 3 doesn't even make sense. You can't reuse variables unless they were declared in a parent scope of the switch statement. This means that if you declare a variable within a case, then it can't be used in another case statement. If you declare a variable above the switch statement (in the parent scope) then it doesn't matter if you use braces or not, case statements will have access to the variable.
  • Max Roncace
    Max Roncace almost 7 years
    Disagree with this. Using braces AND writing code outside the braces would be very bad form, yes, but this doesn't discredit the use of braces in itself.
  • anuragw
    anuragw almost 4 years
    I just (re)discovered that variables declared in case 1 can still be in scope in case 2. Eg: ...case 1: int a = 10; break; case 2: int a = 11; break; ... doesn't compile. (tested with Oracle JDK 8)
  • Petr Dvořák
    Petr Dvořák over 3 years
    The braces are there to prevent exactly the situation you mention in your example...
  • Ben Jones
    Ben Jones over 2 years
    but the braces do create a new scope...