Refactoring if/else logic

前端 未结 14 648
醉话见心
醉话见心 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:32

    Thousands? Maybe a rules engine is what you need. Drools could be a viable alternative.

    Or a Command pattern that encapsulates all the "do something slightly different" logic for each case. Store each Command in a Map with the concatentation of age, location, and other factors as the key. Lookup the Command, execute it, and you're done. Nice and clean.

    The Map can be stored as configuration and read in on start up. You can add new logic by adding new classes and reconfiguring.

提交回复
热议问题