开发者

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:

  • 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 mor开发者_运维百科e verbose?
  • Any better idea?


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.


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.


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;


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.


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜