Menu

Rule:SuspiciousEqualsMethodName - Is this rule valid???

George
2016-01-29
2016-02-06
  • George

    George - 2016-01-29

    could anyone tell me what is wrong with the following code?

    private boolean areEquals(final Object thisObj, final Object thatObj) {
    return thisObj == null && thatObj == null || thisObj != null && thisObj.equals(thatObj);
    }
        @Override
        public boolean equals(final Object var) {
            return var instanceof AttributeKey && areEquals(getEndPoint(), ((AttributeKey) var).getEndPoint())
                    && areEquals(this.getCluster(), ((AttributeKey) var).getCluster());
        }
    

    // I get PMD violation for areEquals?? how can this be fixed ? (Using maven-pmd-plugin:3.0.1)

     
  • Andreas Dangel

    Andreas Dangel - 2016-01-29

    According to the documentation of the rule:

    The method name and parameter number are suspiciously close to equals(Object), which can denote an intention to override the equals(Object) method.

    Your method areEquals sounds and looks similar to the equals method from Object.
    However, I can't reproduce your problem with your given code example - seems you have already renamed your private equals method to areEquals - which got rid of this violation.

    The rule wants to warn you, that you have written an equals method, that does not override the equals method from Object, which you probably wanted to.

    There are different ways, how you could implement this:
    a) Use the framework's method Objects.equals
    b) do not name the method equals - you already did this. You named in areEquals which is different enough to make it clear, that you really didn't want to override equals
    c) Suppress the violation, e.g. annotate the method with @SuppressWarnings('PMD.SuspiciousEqualsMethodName')

    Hope this helps!
    Regards,
    Andreas

     
  • George

    George - 2016-01-29

    ok, thanks very much for your input. Earlier I had equals(Object this, Object that); and it complained . Does it complain even if I try to overloaded version of equals?

     
  • Andreas Dangel

    Andreas Dangel - 2016-02-06

    Yes, it will check for the method name. If you overload it, the method name is still "equals" - and the rule is triggered.

     

Log in to post a comment.

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.