Sonar complaining about private method name in a class when we using the same name of parent private method. In code quality what is the disadvantage of defining a private method with the same name of parent private method?
Or do we need to categorize this as false positive
IMO it's because that could get confusing. Consider below, read the comment:
class Child extends Super{
public void myMethod() {
System.out.println("in child");
}
}
class Super{
public static void main(String[] args) {
Super s = new Child();
s.myMethod(); // At this point you might expect myMethod of child to be called if it'll call the Parent's since it is private.
}
private void myMethod() {
System.out.println("in super");
}
}
When you have some method in your subclass with the same name with your superclass, at the first glance, the assumption will be an override, causing confusion when it is not.
The docs mention three situations when this can happen:
The parent class method is static and the child class method is not.
The arguments or return types of the child method are in different packages than those of the parent method.
The parent class method is private.
And also the recommendation:
But if the intent is truly for the child class method to be different, then the method should be renamed to prevent confusion.
So if you really want to not override the method from superclass, the recommendation is to change it to avoid confusion.
You can check an example in the RSPEC-2177 - Sonar Rule Documentation,
The decision of renaming the method or marking the ocurrence as false positive depends entirely on how the team organise their codebase, and the code convention used between the developers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With