rspec/rules/S2385/rule.adoc

44 lines
1.6 KiB
Plaintext
Raw Normal View History

2021-01-27 13:42:22 +01:00
Mutable ``++stati{cpp}`` members which are accessed directly, rather than through getters and setters, should be protected to the degree possible. That can be done by reducing visibility or making the field ``++final++`` if appropriate. Note that making a mutable field, such as an array, ``++final++`` will keep the variable from being reassigned, but doing so has no effect on the mutability of the internal state of the array (i.e. it doesn't accomplish the goal).
2021-01-27 13:42:22 +01:00
This rule checks that ``++stati{cpp}`` arrays, ``++Collection++``s, ``++Date++``s, and ``++awt.Point++``s are not ``++publi{cpp}`` in classes and enumerations.
== Noncompliant Code Example
----
public class A {
public static String [] strings1 = {"first","second"}; // Noncompliant
public static String [] strings2 = {"first","second"}; // Noncompliant
public static List<String> strings3 = new ArrayList&lt;&gt;(); // Noncompliant
// ...
}
----
== Compliant Solution
----
public class A {
protected static final String [] strings1 = {"first","second"}; // access limited
private static String [] strings2 = {"first","second"}; // made private with getter, setter
private static List<String> strings3 = new ArrayList<>();
public static String [] getStrings2() {
return strings2.clone();
}
public static void setStrings2(String [] strings) {
strings2 = strings.clone();
}
// ...
}
----
== See
* http://cwe.mitre.org/data/definitions/582.html[MITRE, CWE-582] - Array Declared Public, Final, and Static
* http://cwe.mitre.org/data/definitions/607.html[MITRE, CWE-607] - Public Static Final Field References Mutable Object