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:
- Use separate variables `tomatoEater` and `potatoEater`, making the code less maintainable?
- Define `eater` before the `switch`, making it accessible to more than it should?
- Define `eater` the first time only, leading to potential confusion?
- Add braces, making the code more verbose?
- Any better idea?
I would personally either use braces, or just abandon the local variable completely:
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.