Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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

like image 571
Nuhman Paramban Avatar asked Jan 11 '19 16:01

Nuhman Paramban


2 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");
   }
 }
like image 77
Aditya Narayan Dixit Avatar answered Oct 04 '22 22:10

Aditya Narayan Dixit


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.

like image 36
nortontgueno Avatar answered Oct 04 '22 23:10

nortontgueno