Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: revised the second nce/cs as well

...

In this noncompliant code example, the data member total keeps track of total field tracks the total number of elements as they are added and removed from a container using the methods add() and remove() respectively.

...

As a public field, total can be altered by client code independently of the add() and remove() methods.

Compliant Solution (Private Primitive Field)

Accessor methods provide controlled access to fields outside of the package in which their class is declared.  This compliant solution declares total as private and provides a public accessor.  The add() and remove() methods modify its value while preserving class invariants

...

Accessor methods can perform additional functions, such as input validation and security manager checks, before manipulating the state.  Make sure that you do not return references to private mutable objects from accessor methods (see OBJ05-J. Defensively copy private mutable class members before returning their references for details).

Noncompliant Code Example (Public Mutable Field)

...

Code Block
bgColor#FFCCCC
public static final HashMap<Integer, String> hm = new HashMap<Integer, String>();

Compliant Solution (

...

Private Mutable Fields)

Mutable data members that are static internal fields must be declared private:

...

Depending on the required functionality, wrapper accessor methods may retrieve either a reference to the HashMap, a may return a copy of the HashMap, or a value contained by the HashMap. This compliant solution adds a wrapper method to return an accessor method that returns the value of an element given its index in the HashMap.  Make sure that you do not return references to private mutable objects from accessor methods (see OBJ05-J. Defensively copy private mutable class members before returning their references for details).

Exceptions

OBJ01-EX0: According to Sun's Code Conventions document [Conventions 2009]:

...

Risk Assessment

Failing to declare data members private limit field accessibility can defeat encapsulation, allow attackers to manipulate fields to violate class invariants, or allow these fields to be corrupted as the result of concurrent accesses from multiple threads.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

OBJ01-J

Medium

Likely

Medium

P12

L1

...

Detection of public and protected data members fields 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.

...