referencing each case of a switch from a conditional inside a different method in java

偶尔善良 提交于 2019-12-25 00:24:50

问题


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:


Refactor your command enum to classes using the Command pattern.




回答2:


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



来源:https://stackoverflow.com/questions/1219032/referencing-each-case-of-a-switch-from-a-conditional-inside-a-different-method-i

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!