Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are different case condition bodies not in different scope?

Why are different case bodies not automatically in their own scope? For example, if I were to do this:

switch(condition) {
  case CONDITION_ONE:
    int account = 27373;
  case CONDITION_TWO:
    // account var not needed here
  case CONDITION_THREE:
    // account var not needed here
  case CONDITION_FOUR:
    int account = 90384;
}

the compiler would complain about local variable redefinitions. I understand I could do this:

switch(condition) {
  case CONDITION_ONE: {
    int account = 27373;
  }
  case CONDITION_TWO: {
    // account var not needed here
  }
  case CONDITION_THREE: {
    // account var not needed here
  }
  case CONDITION_FOUR: {
    int account = 90384;
  }
}

to put a block around each set of statements to be executed to put each account variable in its own scope. But why doesn't the language do this for me?

Why would you ever want to declare a local variable in CONDITION_ONE's body and then use it in CONDITION_TWO's? This seems like a TERRIBLE idea which should be explicitly banned, not implicitly permitted.

like image 860
Tom Tresansky Avatar asked Aug 27 '10 14:08

Tom Tresansky


2 Answers

Why would you want this? If you need a new scope for each case block, you're doing too much in your case block. Push that off to a method.

like image 190
Randolpho Avatar answered Oct 06 '22 07:10

Randolpho


That would be inconsistent with the rest of the language.

As it is, scope is always determined by blocks. That sort of consistency makes Java easier to read and maintain.

like image 29
erickson Avatar answered Oct 06 '22 07:10

erickson