Nicolas Raoul
Nicolas Raoul

Reputation: 60203

Java style: Variable declaration in a switch

The following code does not compile because eater is defined twice:

switch (vegetable) {
    case TOMATO:
        Eater eater = new Eater(Tomato.class, many parameters);
        eater.eat(more parameters);
        return true;

    case POTATO:
        Eater eater = new Eater(Potato.class, many parameters);
        eater.eat(more parameters);
        return true;

    case CARROT:
        doSomethingElse();
        return true;
}

Should I:

Upvotes: 2

Views: 851

Answers (5)

Colin Hebert
Colin Hebert

Reputation: 93157

Maybe using a switch isn't such a good idea at all.


In what better example can represent a switch statement in Java ?

Upvotes: 0

CurtainDog
CurtainDog

Reputation: 3205

Not quite the same logic as your method (carrot is treated as default) but shows an alternative approach (with some more behind the scenes wiring that I haven't worried about here):

Eater eater = vegetable.getEater(many parameters);
if (eater != null) eater.eat(more parameters);
else doSomethingElse();
return true;

Upvotes: 1

Joel
Joel

Reputation: 16655

How would using separate variables make the code less maintainable? (first bullet point). If anything I would say it would do the opposite as the variable name better explains what it is. I would go with that if keeping it in that scope is important to you.

Upvotes: 0

Nivas
Nivas

Reputation: 18344

Why not this:

switch (vegetable) 
{ 
    case TOMATO: 
        new Eater(Tomato.class, many parameters).eat(more parameters); 
        return true; 

    case POTATO: 
        new Eater(Potato.class, many parameters).eat(more parameters); 
        return true; 

    case CARROT: 
        doSomethingElse(); 
        return true; 
} 

If you dont have any use of the Eater reference anywhere else later, I would do this.

Upvotes: 2

Jon Skeet
Jon Skeet

Reputation: 1500055

I would personally either use braces, or just abandon the local variable completely:

new Eater(Potato.class, many parameters)
     .eat(more parameters);

The disadvantage of this is that it makes it a little harder to debug. Obviously this isn't your real code though... which makes it hard to say the right thing to do. It's quite possible that the right thing to do is actually to break out the bodies of the cases into separate methods.

Upvotes: 6

Related Questions