rspec/rules/S1068/java/rule.adoc

83 lines
2.1 KiB
Plaintext
Raw Normal View History

== Why is this an issue?
2021-01-27 13:42:22 +01:00
If a ``++private++`` field is declared but not used in the program, it can be considered dead code and should therefore be removed. This will improve maintainability because developers will not wonder what the variable is used for.
2020-06-30 12:47:33 +02:00
2021-02-02 15:02:10 +01:00
2021-01-27 13:42:22 +01:00
Note that this rule does not take reflection into account, which means that issues will be raised on ``++private++`` fields that are only accessed using the reflection API.
2020-06-30 12:47:33 +02:00
=== Noncompliant code example
2020-06-30 12:47:33 +02:00
2022-02-04 17:28:24 +01:00
[source,java]
2020-06-30 12:47:33 +02:00
----
public class MyClass {
private int foo = 42;
public int compute(int a) {
return a * 42;
}
}
----
=== Compliant solution
2020-06-30 12:47:33 +02:00
2022-02-04 17:28:24 +01:00
[source,java]
2020-06-30 12:47:33 +02:00
----
public class MyClass {
public int compute(int a) {
return a * 42;
}
}
----
=== Exceptions
2020-06-30 12:47:33 +02:00
The rule admits 3 exceptions:
* Serialization id fields
2021-01-27 13:42:22 +01:00
The Java serialization runtime associates with each serializable class a version number, called ``++serialVersionUID++``, which is used during deserialization to verify that the sender and receiver of a serialized object have loaded classes for that object that are compatible with respect to serialization.
2021-02-02 15:02:10 +01:00
2021-01-27 13:42:22 +01:00
A serializable class can declare its own ``++serialVersionUID++`` explicitly by declaring a field named ``++serialVersionUID++`` that must be static, final, and of type long. By definition those ``++serialVersionUID++`` fields should not be reported by this rule:
2020-06-30 12:47:33 +02:00
2021-02-02 15:02:10 +01:00
2020-06-30 12:47:33 +02:00
----
public class MyClass implements java.io.Serializable {
private static final long serialVersionUID = 42L;
}
----
* Annotated fields
The unused field in this class will not be reported by the rule as it is annotated.
----
public class MyClass {
@SomeAnnotation
private int unused;
}
----
* Fields from classes with native methods
The unused field in this class will not be reported by the rule as it might be used by native code.
----
public class MyClass {
private int unused = 42;
private native static void doSomethingNative();
}
----
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
include::../message.adoc[]
'''
== Comments And Links
(visible only on this page)
include::../comments-and-links.adoc[]
endif::env-github,rspecator-view[]