rspec/rules/S2388/java/rule.adoc

80 lines
2.1 KiB
Plaintext

== Why is this an issue?
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.
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.
== 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 doSomething() {
foo(); // Noncompliant, it is not explicit if Outer#foo or Parent#foo is the intended implementation to be called.
// ...
}
}
}
----
==== Compliant solution
[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 doSomething() {
super.foo(); // Compliant, it is explicit that Parent#foo is the desired implementation to be called.
// ...
}
}
}
----
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
=== Message
Prefix this call to "xxx" with "super.".
'''
== Comments And Links
(visible only on this page)
=== on 27 Jan 2015, 20:15:19 Freddy Mallet wrote:
+1 to activate this rule by default.
endif::env-github,rspecator-view[]