Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

It is difficult to control how data members declared public or protected are accessed. Attackers can manipulate such members in unexpected ways. As a result data members must be declared private. Use wrapper accessor methods to expose class members that are to be accessed outside of the package in which their class is declared. Using wrapper methods enables appropriate monitoring and control of the modification of data members (for example, by defensive copying, validating input, and logging). The wrapper methods can preserve class invariants.

Noncompliant Code Example (Public Primitive Field)

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

Code Block
bgColor#FFCCCC

public class Widget {
  public int total; // Number of elements

  void add() {
    if (total < Integer.MAX_VALUE) {      
      total++;
      // ...
    } else {
      throw new ArithmeticException("Overflow");
    }
  }

  void remove() {  
    if (total > 0) {      
      total--;
      // ...
    } else {
      throw new ArithmeticException("Overflow");
    }
  }
}

As a public data member, total can be altered by external code independently of the add() and remove() methods. It is bad poor practice to expose fields from a public class [Bloch 2008].

...

This compliant solution declares total as private and provides a public accessor so that the required member can be accessed beyond the current package. The add() and remove() methods modify its value without violating any class invariants.

Note that care must be taken when providing references to private mutable objects from accessor methods ; (see rule OBJ05-J. Defensively copy private mutable class members before returning their references for details).

Code Block
bgColor#ccccff

public class Widget {
  private int total; // Declared private

  public int getTotal () {
    return total;
  }

  // definitionsDefinitions for add() and remove() remain the same
}

It is good practice to use methods such as add(), remove(), and getTotal() to manipulate the private internal state. These methods can perform additional functions, such as input validation and security manager checks, prior to before manipulating the state.

Noncompliant Code Example (Public Mutable Field)

This noncompliant code example shows a static mutable hash map with public accessibility. :

Code Block
bgColor#FFCCCC

public static final HashMap<Integer, String> hm = new HashMap<Integer, String>();

...

Mutable data members that are static must be declared private.:

Code Block
bgColor#ccccff

private static final HashMap<Integer, String> hm = new HashMap<Integer, String>();

public static String getElement(int key) { 
  return hm.get(key);
}

...

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 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.

...

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

OBJ01-J

medium Medium

likely Likely

medium Medium

P12

L1

Automated Detection

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.

...

SEI CERT C++ Coding Standard

OOP00-CPP. Declare data members private

MITRE CWE

CWE-766. Critical variable declared public , 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

[Bloch 2008]

Item 13. , "Minimize the accessibility Accessibility of classes and members; Classes and Members"
Item 14. In public classes, use accessor methods, not public fields , "In Public Classes, Use Accessor Methods, Not Public Fields"

[JLS 2005]

§6.6, Access Control

[Long 2005]

§2Section 2.2, "Public Fields"

 

...

OBJ00-J. Limit extensibility of classes and methods with invariants