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

前端 未结 18 2019
温柔的废话
温柔的废话 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:00

    Looking at the campaign, it's very poorly explained. There's nothing wrong with ifs, but in certain cases they can indicate that you're not using OOP to its full potential.

    What the campaign is trying to promote is increased use of polymorphism in order to decouple calling code from the type of object it is looking at.

    You would use some smarter object instead of s being a string:

    interface I {
      public String getName();
      public void doSomething();
    }
    
    class A implements I {
      public String getName() { return "one"; }
      public void doSomething() { ...; }
    }
    
    class B implements I {
      public String getName() { return "two"; }
      public void doSomething() { ...; }
    }
    

    Then you can replace the ifs with:

    I obj = ...get an A or B from somewhere...;
    obj.doSomething();
    

提交回复
热议问题