do this without using an “if” | if(s == “value1”){…} else if(s == “value2”) { …}

前端 未结 18 2149
温柔的废话
温柔的废话 2021-01-30 09:36

According to anti-if campaign it is a best practice not to use ifs in our code. Can anyone tell me if it possible to get rid of the if in this piece of code ? (switch is also

18条回答
  •  自闭症患者
    2021-01-30 10:01

    Make use of the strategy pattern.

    In Java terms:

    public interface Strategy {
        void execute();
    }
    
    public class SomeStrategy implements Strategy {
        public void execute() {
            System.out.println("Some logic.");
        }
    }
    

    which you use as follows:

    Map strategies = new HashMap();
    strategies.put("strategyName1", new SomeStrategy1());
    strategies.put("strategyName2", new SomeStrategy2());
    strategies.put("strategyName3", new SomeStrategy3());
    
    // ...
    
    strategies.get(s).execute();
    

提交回复
热议问题