Refactoring if/else logic

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

    Use OOP Concepts: This is dependent of the rest of the design, but maybe you should have a user interface, Student,Admin interfaces the extends it and UsaStudent,MexicoStudent,UsaAdmin,MexicoAdmin implementation that do some stuff. Hold a User instance and just call its doStuff method.

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

    without more information there is no good answer

    but fair guess would be this: use OO

    first define a User, define Admin, Student and all other types of users and then let polymorphism take care of the rest

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

    You could make userType an enum, and give it a method that performs all of your "do something slightly different" actions.

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

    If the code in the blocks fits within a few standard patterns, I would create a table with columns (type, location, minAge, maxAge, action), where 'action' is an enum indicating which of several types of processing to do. Ideally, this table would be read from a data file or kept in SQL.

    Then, you can just do a table lookup in the Java code to determine the action to take for a user.

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

    I would probably first check whether you can parametrize the code doStuff and doSimilarStuff.

    0 讨论(0)
  • 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.

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