rspec/rules/S2156/java/rule.adoc

69 lines
1.6 KiB
Plaintext
Raw Normal View History

== Why is this an issue?
The difference between ``++private++`` and ``++protected++`` visibility is that child classes can see and use ``++protected++`` members, but they cannot see ``++private++`` ones. Since a ``++final++`` class will have no children, marking the members of a ``++final++`` class ``++protected++`` is confusingly pointless.
2020-06-30 12:48:07 +02:00
Note that the ``++protected++`` members of a class can also be seen and used by other classes that are placed within the same package, this could lead to accidental, unintended access to otherwise private members.
=== Noncompliant code example
[source,java]
----
public final class MyFinalClass {
protected String name = "Fred"; // Noncompliant
protected void setName(String name) { // Noncompliant
// ...
}
----
=== Compliant solution
[source,java]
----
public final class MyFinalClass {
private String name = "Fred";
public void setName(String name) {
// ...
}
----
2020-06-30 12:48:07 +02:00
=== Exceptions
2020-06-30 12:48:07 +02:00
Members annotated with ``++@VisibleForTesting++`` annotation are ignored, as it indicates that visibility has been purposely relaxed to make the code testable.
2021-02-02 15:02:10 +01:00
[source,java]
2020-06-30 12:48:07 +02:00
----
public final class MyFinalClass {
@VisibleForTesting
protected Logger logger; // Compliant
@VisibleForTesting
protected int calculateSomethingComplex(String input) { // Compliant
// ...
}
}
----
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
include::../message.adoc[]
include::../highlighting.adoc[]
'''
== Comments And Links
(visible only on this page)
include::../comments-and-links.adoc[]
endif::env-github,rspecator-view[]