You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 21 Next »

If data members are declared public or protected, it is difficult to control how they are accessed. It is possible that they can be manipulated in unintended ways, with undefined consequences. If they need to be exposed beyond the class they are declared in, acceessor methods may be used. Also, with the use of setter methods, modification of data members can be monitored as appropriate (e.g., by defensive copying, validating input, logging and so on). Methods that are declared public or protected must preserve the invariants of the class and their use should not be abused.

Noncompliant Code Example

In this noncompliant code example, the data member total is meant to keep track of the total number of elements as they are added and removed from a container. However, as a public data member, total can be altered by external code, independent of these actions.

public class Widget {
  public int total;
  void add (SomeType someParameter) {
    total++;
    // ...
  }
  void remove (SomeType someParameter) {
    total--;
    // ...
  }
}

Compliant Solution

This compliant solution declares total as private and provides a public accessor. The method add() modifies its value without violating class invariants.

public class Widget {
  private int total;
  void add (someType someParameter) {
    total++;
    // ...
  }
  void remove (someType someParameter) {
    total--;
    // ...
  }
  public int getTotal () {
    return total;
  }
}

Exceptions

EX1: According to [[Conventions 09]]:

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 supported struct), then it's appropriate to make the class's instance variables public.

Risk Assessment

Failing to declare data members private can break encapsulation.

Recommendation

Severity

Likelihood

Remediation Cost

Priority

Level

OBJ00- J

medium

likely

medium

P12

L1

Automated Detection

TODO

Related Vulnerabilities

Search for vulnerabilities resulting from the violation of this rule on the CERT website.

Other Languages

This rule appears in the C++ Secure Coding Standard as OBJ00-CPP. Declare data members private.

References

[[JLS 06]] Section 6.6, Access Control
[[SCG 07]] Guideline 3-2 Define wrapper methods around modifiable internal state
[[Long 05]] Section 2.2, Public Fields
[[Bloch 08]] Items 13: Minimize the accessibility of classes and members; 14: In public classes, use accessor methods, not public fields


07. Object Orientation (OBJ)      07. Object Orientation (OBJ)      OBJ01-J. Understand how a superclass can affect a subclass

  • No labels