重构if / else逻辑 [英] Refactoring if/else logic

查看:211
本文介绍了重构if / else逻辑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有千行if / else逻辑方法的java类,如下所示:

I have a java class with a thousand line method of if/else logic like this:

if (userType == "admin") {
     if (age > 12) {
          if (location == "USA") {
               // do stuff
          } else if (location == "Mexico") {
               // do something slightly different than the US case
          }
     } else if (age < 12 && age > 4) {
          if (location == "USA") {
               // do something slightly different than the age > 12 US case
          } else if (location == "Mexico") {
               // do something slightly different
          }
     }
 } else if (userType == "student") {
     if (age > 12) {
          if (location == "USA") {
               // do stuff
          } else if (location == "Mexico") {
               // do something slightly different than the US case
          }
     } else if (age < 12 && age > 4) {
          if (location == "USA") {
               // do something slightly different than the age > 12 US case
          } else if (location == "Mexico") {
               // do something slightly different
          }
     }

我应该如何将其重构为更易于管理的内容?

How should I refactor this into something more managable?

推荐答案

您应该使用策略,可能在枚举中实施,例如:

You should use Strategies, possibly implemented within an enum, e.g.:

enum UserType {
  ADMIN() {
    public void doStuff() {
      // do stuff the Admin way
    }
  },
  STUDENT {
    public void doStuff() {
      // do stuff the Student way
    }
  };

  public abstract void doStuff();
}

作为每个最外层的代码结构 if 分支看起来几乎相同,在下一步重构中,您可能希望使用模板方法。或者,您也可以将位置(也可能是年龄)转换为策略。

As the code structure within each outermost if branch in your code looks pretty much the same, in the next step of refactoring you might want to factor out that duplication using template methods. Alternatively, you might turn Location (and possibly Age) into a strategy as well.

更新:在Java4中,您可以实现 typesafe enum ,并使用普通的旧子类来实现不同的策略。

Update: in Java4, you can implement a typesafe enum by hand, and use plain old subclassing to implement the different strategies.

这篇关于重构if / else逻辑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆