Search code examples
javasonarqube

How to reduce cognitive complexity of a method


I want to reduce cognitive complexity of the following method. How to do it ? To my point of view, I can't, but I am unexperienced in the matter

@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;
}

Solution

  • You can use Java's Objects.equals to check equality of fields easily. It will return true if both given objects are equal or both are null, else 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)
      && ...;
    

    As an alternative there's Apache Commons EqualsBuilder which also provides a reflectionEquals method that automatically gets all fields from your class and compares them. Though this approach might be slower because of reflection and you have less control over what's happening.