Using Case Statements

java, switch-statement

Solution

Nesting won't cause trouble down the line exactly, but it can be confusing to read. Adding comments and/or other documentation will really help future coders (and yourself in a week!) understand this by looking at it.

The lack of a break isn't a bad practice by itself, but it is something that -most- case statements have, so I would add a comment at the end like `// no break, allow fall-through`.

So both cases boil down to good documentation.

These points are perpendicular to the fact that I don't think this code does what you think it will do.

The `case` clause is not reevalauted every time you come across one - they're just points to jump to for the switch. So in your example, you will always end up in `case 1` if you start at `case 0` - you'll never end up at `case 2` from `case 0`.

If I were to restructure this, here's what I would do. Instead of using `int`, I would use `enum`:

enum Foo { GOOD_FOO, BAD_FOO }
enum Switcharoo { BAR, BAZ, BAQ, ESCAPE }
enum Size { NONE, REGULAR, BIGGER }

Foo foo = ... // assigned somewhere
Switcharoo roo = ... // assigned somewhere
Size size = NONE;

// use a while loop to reevalulate roo with each pass
while(roo != Switcharoo.ESCAPE) {
    switch(roo){
        case BAR:
                switch(foo) {
                    case GOOD_FOO: foo = doSomething(foo); break;
                    case BAD_FOO: foo = doSomethingElse(foo); break;
                }
            break;
        case BAZ:
            roo = Switcharoo.ESCAPE;
            size = Size.REGULAR;
            break;
        case BAQ:
            roo = Switcharoo.ESCAPE;
            size = Size.BIGGER;
            break;

    }
}

Problem

I'm using int[] arrays as a reference. I wondering if my use of case statements is sound or if it will cause errors down the line. This is my code: ``` int switcheroo = intarray[0]; int foo = intarray[1]; boolean size = false; boolean biggersize = false; switch (switcheroo) { case 0: switch (foo) { case 1: doSomething(switcheroo); //change switcheroo somehow. break; case 2: doSomethingElse(switcheroo); //change switcheroo differently. break; } case 1: size = true; break; case 2: biggersize = true; break; default: break; } ``` Unless it's a coincidence, this is working to ripple the changes from the nested case statement into the other cases, as I want. My questions are: Will this nesting causes trouble further down the line? Is the lack of a break; after a case bad practice? Thanks. Edit: The methods which change switcheroo in the middle of the switch statements were put there for responses to that. I will not be doing this is my program.

Original source