Modify rule S2388: Update in line with LayC (SONARJAVA-4495) (#2821)
This commit is contained in:
parent
a278258b88
commit
c34d9d9db6
@ -1,24 +1,34 @@
|
||||
== Why is this an issue?
|
||||
|
||||
When an inner class extends another class, and both its outer class and its parent class have a method with the same name, calls to that method can be confusing. The compiler will resolve the call to the superclass method, but maintainers may be confused, so the superclass method should be called explicitly, using ``++super.++``.
|
||||
An inner class that extends another type can call methods from both the outer class and parent type directly, without prepending `super.` or `Outer.this.`.
|
||||
|
||||
When both the outer and parent classes contain a method with the same name, the compiler will resolve an unqualified call to the parent type's implementation.
|
||||
The maintainer or a future reader may confuse the method call as calling the outer class's implementation, even though it really calls the super type's.
|
||||
|
||||
=== Noncompliant code example
|
||||
To make matters worse, the maintainer sees the outer class's implementation in the same file as the call in the inner class, while the parent type is often declared in another file.
|
||||
The maintainer may not even be aware of the ambiguity present, as they do not see the parent's implementation.
|
||||
|
||||
[source,java]
|
||||
== How to fix it
|
||||
|
||||
Explicitly call the super type's method by prepending `super.` to the method call.
|
||||
If the intention was to call the outer class's implementation, prepend `Outer.this.` instead.
|
||||
|
||||
=== Code examples
|
||||
|
||||
==== Noncompliant code example
|
||||
|
||||
[source,java,diff-id=1,diff-type=noncompliant]
|
||||
----
|
||||
public class Parent {
|
||||
public void foo() { ... }
|
||||
}
|
||||
|
||||
public class Outer {
|
||||
|
||||
public void foo() { ... }
|
||||
|
||||
public class Inner extends Parent {
|
||||
|
||||
public void doTheThing() {
|
||||
foo(); // Noncompliant; was Outer.this.foo() intended instead?
|
||||
public void doSomething() {
|
||||
foo(); // Noncompliant, it is not explicit if Outer#foo or Parent#foo is the intended implementation to be called.
|
||||
// ...
|
||||
}
|
||||
}
|
||||
@ -26,22 +36,20 @@ public class Outer {
|
||||
----
|
||||
|
||||
|
||||
=== Compliant solution
|
||||
==== Compliant solution
|
||||
|
||||
[source,java]
|
||||
[source,java,diff-id=1,diff-type=compliant]
|
||||
----
|
||||
public class Parent {
|
||||
public void foo() { ... }
|
||||
}
|
||||
|
||||
public class Outer {
|
||||
|
||||
public void foo() { ... }
|
||||
|
||||
public class Inner extends Parent {
|
||||
|
||||
public void doTheThing() {
|
||||
super.foo();
|
||||
public void doSomething() {
|
||||
super.foo(); // Compliant, it is explicit that Parent#foo is the desired implementation to be called.
|
||||
// ...
|
||||
}
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user