Refactoring if/else logic

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

    The first thing I would do with this code is create the types Admin and Student, both of which inherit from the base type User. These classes should have a doStuff() method where you hide the rest of this logic.

    As a rule of thumb, any time you catch yourself switching on type, you can use polymorphism instead.

提交回复
热议问题