...
As a public data member, total
can be altered by external code independently of the add()
and remove()
methods. It is bad practice to expose fields from a public class [Bloch 2008].
Compliant Solution (Private)
...
OBJ01-EX0: According to Sun's Code Conventions document [Conventions 2009]:
One example of appropriate public instance variables is the case where the class is essentially a data structure, with no behavior. In other words, if you would have used a
struct
instead of a class (if Java supportedstruct
), then it's appropriate to make the class's instance variablespublic
.
OBJ01-EX1: "If a class is package-private or is a private
nested class, there is nothing inherently wrong with exposing its data fields – assuming they do an adequate job of describing the abstraction provided by the class. This approach generates less visual clutter than the accessor-method approach, both in the class definition and in the client code that uses it" [Bloch 2008]. This exception applies to both mutable and immutable fields.
...
Detection of public and protected data members is trivial; heuristic detection of the presence or absence of accessor methods is straightforward. However, simply reporting all detected cases without suppressing those cases covered by the exceptions to this rule would produce excessive false positives. Sound detection and application of the exceptions to this rule is infeasible; however, heuristic techniques may be useful.
Related Guidelines
CWE-766. Critical variable declared public | |
Secure Coding Guidelines for the Java Programming Language, Version 3.0 | Guideline 3-2. Define wrapper methods around modifiable internal state |
Bibliography
Item 13. Minimize the accessibility of classes and members; Item 14. In public classes, use accessor methods, not public fields | |
[JLS 2005] | |
§2.2, Public Fields |
...
OBJ00-J. Limit extensibility of classes and methods with invariants Rule 05: Object Orientation (OBJ)