Sonar Rename this method; there is a "private" method in the parent class with the same name

Viewed 1822

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

4 Answers

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.

IHMO, this rule is a no sense.
If the naming makes sense for both the parent and the subclass, you will not invent a different name for one of these to make Sonar happy.
It could make code less clear and also make it less homogeneous in your base code. Private methods are visible only inside the current class, so it is enough to make this choice safe.

I understand the purpose for the rule. However, it should not apply to abstract classes with concrete private methods.

We are using the Apache MINA library, which has several concrete private methods in CumulativeProtocolDecoder that are referenced inside their public concrete methods. If the public methods are overridden, we are forced to provide our own implementations of the private methods. It doesn't make sense to name them something else just to avoid being dressed down by Sonar.

Related