如何降低方法的认知复杂性

我想降低以下方法的认知复杂性。怎么做 ?在我看来,我不能,但我在这方面没有经验

@Override
public boolean equals(Object obj) {
    if (this == obj) return true;
    if (obj == null) return false;
    if (!(obj instanceof Bean)) return false;
   Bean other = (Bean) obj;
    if (property1== null) {
        if (other.property1!= null) return false;
    } else if (!property1.equals(other.property1)) return false;
    if (property2== null) {
        if (other.property2!= null) return false;
    } else if (!property2.equals(other.property2)) return false;
    if (property3== null) {
        if (other.property3!= null) return false;
    } else if (!property3.equals(other.property3)) return false;
    if (property4== null) {
        if (other.property4!= null) return false;
    } else if (!property4.equals(other.property4)) return false;
    return true;
}

回答

您可以使用 JavaObjects.equals轻松检查字段的相等性。true如果两个给定的对象相等或都相等,它将返回null,否则返回false

if (this == obj) return true;
if (obj == null || this.getClass() != obj.getClass()) return false;
Bean other = (Bean) obj;
return Objects.equals(this.property1, other.property1)
  && Objects.equals(this.property2, other.property2)
  && ...;

作为替代方案,Apache CommonsEqualsBuilder还提供了一种reflectionEquals方法,可以自动从您的类中获取所有字段并进行比较。尽管由于反射,这种方法可能会更慢,并且您对正在发生的事情的控制较少。


以上是如何降低方法的认知复杂性的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>