如何在不增加圈复杂度的情况下覆盖等于?

hec*_*o84 5 java overriding equals

我最近覆盖了equals我最近的Java项目的域对象中的一些方法.当我们使用Sonar计算我们的代码度量时,我立即看到这些类的圈复杂度增加到阈值以上.

我想知道是否有一种聪明的方式,模式或选项可以保持这个指标低,尽管有一些更复杂的equals方法.

编辑:这是我的一个例子,我没有具体说明,只是为了让我们知道我们在谈论什么.

@Override
public boolean equals(Object o) {
  if (o instanceof MyKey) {
  MyKey other = (MyKey) o;
  if (this.foo.longValue() == other.getFoo().longValue() &&
    this.bar.equalsIgnoreCase(other.getBar()) &&
    this.foobar.shortValue() == other.getFoobar().longValue()){
    return true;
    }
  }
  return false;
}

@Override
public int hashCode() {
  int hash = 3;
  hash = 53 * hash + foo.hashCode();
  hash = 53 * hash + bar.hashCode();
  hash = 53 * hash + foobar.hashCode();
  return hash;
}
Run Code Online (Sandbox Code Playgroud)

joh*_*384 6

你可以使用Apache的EqualsBuilder:

public boolean equals(Object obj) {
  if (obj == null) { return false; }
  if (obj == this) { return true; }
  if (obj.getClass() != getClass()) {
    return false;
  }
  MyClass rhs = (MyClass) obj;
  return new EqualsBuilder()
             .appendSuper(super.equals(obj))
             .append(field1, rhs.field1)
             .append(field2, rhs.field2)
             .append(field3, rhs.field3)
             .isEquals();
}
Run Code Online (Sandbox Code Playgroud)