Refactoring if/else logic

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

    You really need to break these cases into object methods. I'm assuming these strings and numbers are being pulled out of a database. Instead of using them in their raw form in giant nested conditional logic, you need to use these pieces of data to construct objects that model the desired interactions. Consider a UserRole class with a StudentRole and AdminRole subclasses, a Region class with USA and Mexico subclasses, and an AgeGroup class with appropriate partitioned subclasses.

    Once you have this object oriented structure in place, you'll be able to make use of well understood object oriented design patterns to re-factor this logic.

提交回复
热议问题