When data members are declared public
or protected
, it is difficult to control how they are accessed. Malicious callers Attackers can manipulate such members in unintended ways. Use wrapper accessor methods to expose class members beyond the package in which their class is declared. The use of wrapper methods enables appropriate monitoring and control of the modification of data members (e.g.for example, by defensive copying, validating input, and logging and so on). The wrapper methods must preserve the invariants of the class at all times.
...
Wiki Markup |
---|
However, as a {{public}} data member, {{total}} can be altered by external code, independent of these actions. This noncompliant code example violates the condition that {{public}} classes must not expose data members by declaring them {{public}}. It is a bad practice to expose both mutable as well asand immutable fields from a {{public}} class \[[Bloch 2008|AA. Bibliography#Bloch 08]\]. |
...
It is good practice to use wrapper methods, such as add()
, remove()
, and getTotal
, to manipulate the private internal state because the methods can perform additional functions, such as input validation and security manager checks, prior to manipulating the state.
...
Wiki Markup |
---|
*OBJ00-EX2:* "if a class is package-private or is a {{private}} nested class, there is nothing inherently wrong with exposing its data fields - assumingfieldsâ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|AA. Bibliography#Bloch 08]\]. This exception applies to both mutable as well asand immutable fields. |
OBJ00-EX3: Static final fields that contain values of mathematical constants may be declared public.
...
Search for vulnerabilities resulting from the violation of this guideline on the CERT website.
Other Languages
Related Guidelines
This guideline appears in the C++ Secure Coding Standard as : OOP00-CPP. Declare data members private.
Bibliography
Wiki Markup |
---|
\[[JLS 2006|AA. Bibliography#JLS 06]\] Section 6.6, Access Control \[[SCG 2007|AA. Bibliography#SCG 07]\] Guideline 3-2 Define wrapper methods around modifiable internal state \[[Long 2005|AA. Bibliography#Long 05]\] Section 2.2, Public Fields \[[Bloch 2008|AA. Bibliography#Bloch 08]\] Items 13: Minimize the accessibility of classes and members; 14: In public classes, use accessor methods, not public fields |
...