Question

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.

Was it helpful?

Solution

Refactor your command enum to classes using the Command pattern.

OTHER TIPS

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).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top