I tested this using SonarQube v9.3.0.51899
I got the following sonar issue while creating my own implementation of the interface
CriteriaBuilder
, from the JPA API:
Methods should not be named “tostring”, “hashcode” or “equal”
Either override Object.equals(Object obj), or totally rename the method to prevent any confusion.
Here is how the relevant methods look like:
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.Expression;
import javax.persistence.criteria.Predicate;
// A lot more imports here
public class MyCriteriaBuilder implements CriteriaBuilder {
A lot of other method implementations here
@Override
public Predicate equal(Expression<?> exprsn, Expression<?> exprsn1) {
throw new UnsupportedOperationException("Not supported yet.");
@Override
public Predicate equal(Expression<?> exprsn, Object o) {
throw new UnsupportedOperationException("Not supported yet.");
Another lot of other method implementations here
The rule suggests me to:
Either override Object.equals(Object obj), or totally rename the method to prevent any confusion.
But I can’t override Object.equals, it is not the method I need to override. And I can’t rename the method in my implementation. I can’t rename the method in the public interface, either, as I have no control over the JPA API. So clearly a false positive, at least from my point of view: I can’t do nothing to improve the code.
I would like to suggest to not raise this issue for methods that correctly override a method of a superclass or interface.
The explanation for the rule gives us two scenarios:
This is a bug in which we didn’t override the method we wanted to. This can’t be the case if we did correctly override a method. If there is a bug it wouldn’t be here, but in the superclass that first defined that method.
Done on purpose, but a bad choice for a method name. I agree with this but, again, the choice is not being made here, but in the superclass or interface. Sometimes (as in the example above) we are not in control of the superclass/interface, so there is no point in raising an issue in the subclass method. If the developer is actually in control of the name of the method, he would see this issue being raised in the method of the superclass that first defined it, which is where it can be fixed. So no false-negatives would be generated by this change.
Hey @xurxo ,
Indeed, I can’t believe we didn’t see this earlier. Thanks a lot for the precise reproducer. You are perfectly right, in case of override, you can not change the signature, liking the method name or not. This is an obvious FP that we need to fix.
Here is the ticket related to your issue: [SONARJAVA-4204] FP on S1221 when a method is overridden - SonarSource