Refactoring if/else logic

前端 未结 14 530
醉话见心
醉话见心 2020-11-30 01:38

I have a java class with a thousand line method of if/else logic like this:

if (userType == \"admin\") {
     if (age > 12) {
          if (location == \"         


        
相关标签:
14条回答
  • 2020-11-30 02:36

    You may use Chain of Responsibility pattern.

    Refactor if-else statements into classes with an interface IUserController for instance.

    Initialize your chain within a list or a tree or any suitable data structure, and execute desired functionality in this chain. You may use Builder pattern to create mentioned data structure. It resembles to strategy pattern but in chain of responsibility pattern, an instance in the chain can call linked instance(s).

    Moreover, you can model location specific functionality by using strategy pattern. Hope it helps.

    0 讨论(0)
  • 2020-11-30 02:39

    You should use Strategies, possibly implemented within an enum, e.g.:

    enum UserType {
      ADMIN() {
        public void doStuff() {
          // do stuff the Admin way
        }
      },
      STUDENT {
        public void doStuff() {
          // do stuff the Student way
        }
      };
    
      public abstract void doStuff();
    }
    

    As the code structure within each outermost if branch in your code looks pretty much the same, in the next step of refactoring you might want to factor out that duplication using template methods. Alternatively, you might turn Location (and possibly Age) into a strategy as well.

    Update: in Java4, you can implement a typesafe enum by hand, and use plain old subclassing to implement the different strategies.

    0 讨论(0)
提交回复
热议问题