views:

190

answers:

2

Hello, I am implementing some methods which use switch statements to distinguish between different cases:

private void doThis(){
    switch(command){
    case on: {status = doCalculationsA; break;}
    case off: {status = doCalculationsB; break;}
    case idle: {status = doCalculationsC; break;}
    case stdby:{status = doCalculationsD; break;}   
    }
}

The above works fine, when, further down the business logic, I call doThis() inside other methods which need the doThis() functionality.

However, at this moment I am a bit confused how to incorporate other conditions/restrictions posed on each case of the above switch.

I mean, when I call doThis() within say biggerOperation(), I have new conditions that need to be applied against each case of the switch belonging in the doThis() function:

Sample logic:

biggerOperation(){

    doThat();
    doTheOther();

    if(somethingIsTrue){
      execute "case: on" of doThis()
    }
    else if(somethingElseIsTrue){
      execute "case: off" of doThis()
    }
    else if(aThirdThingIsTrue){
      execute "case: idle" of doThis()
    }
    else if(aFourthThingIsTrue){
      execute "case: stdby" of doThis()
    }
}

I have not been able to figure out an elegant, clean and compact way to do this as of now. Are there any ideas perhaps? How can I explicitly target each case of a switch? Could I use a new switch to implement that conditional logic?

Any suggestions are welcome. Much appreciate your help.

+1  A: 

Refactor your command enum to classes using the Command pattern.

Matt Howells
Thanks for your input. If you don't mind, could you perhaps explain a bit more about the new logic? Using the command pattern, you mean encapsulate method invocation?
denchr
see this question: http://stackoverflow.com/questions/1199646/long-list-of-if-statements-in-java/1199677
Rich Seller
Yes, it looks quite similar. Thank you for pointing it out!
denchr
@Rich: thanks :)
Matt Howells
A: 

You could start doing something like

public MyCreatedEnum getCommand() {
    if(somethingIsTrue){
      return MyCreatedEnum.on;
    }
    else if(somethingElseIsTrue){
      return MyCreatedEnum.off
    }
    else if(aThirdThingIsTrue){
      return MyCreatedEnum.idle
    }
    else if(aFourthThingIsTrue){
      return MyCreatedEnum.stdby
    }
}

private void doThis(){
    MyCreatedEnum command = getCommand();
    switch(command){
    case MyCreatedEnum.on: {status = doCalculationsA; break;}
    case MyCreatedEnum.off: {status = doCalculationsB; break;}
    case MyCreatedEnum.idle: {status = doCalculationsC; break;}
    case MyCreatedEnum.stdby:{status = doCalculationsD; break;}   
    }
}

public void biggerOperation(){
    doThat();
    doTheOther();
    doThis();
}

Then do some more refactoring. But I think this is a good starting point (considering you're not annoyed with 4 nested if elses and 4 switch cases).

Samuel Carrijo
this looks promising. Will give it a try!
denchr