Refactoring if/else logic

前端 未结 14 614
醉话见心
醉话见心 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.

提交回复
热议问题