If data members are declared public or protected, it is difficult to control how they are accessed. It is possible that they could be manipulated in unintented ways, with undefined consequences. Better is to declare all data members private and define accessor functions that control their uses to those intended. Also, modification of data members can be monitored as appropriate (e.g., by logging). Public modifier functions should preserve any invariants of the type.
public class Widget {
public int total;
// ...
void add (someType someParameters) {
// ...
total++;
// ...
}
void remove (someType someParameters) {
// ...
total--;
// ...
}
// ...
}
|
In this example, the data member total is meant to keep track of the total number of elements as they are added and removed. However, as a public data member, it can be altered by any other part of the system independently of those actions.
public class Widget {
private int total;
// ...
void add (someType someParameters) {
// ...
total++;
// ...
}
void remove (someType someParameters) {
// ...
total--;
// ...
}
// ...
public int getTotal () {
return total;
}
// ...
}
|
Now, total is private, and the functions that modify its value preserve any class invariants.
Not properly managing resources could lead to an attacker causing unintended behavior.
Recommendation |
Severity |
Likelihood |
Remediation Cost |
Priority |
Level |
|---|---|---|---|---|---|
OBJ00-J |
medium |
likely |
medium |
P12 |
L1 |
TODO
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
\[[JLS 06|AA. Java References#JLS 06]\] Section 6.6, Access Control \[[SCG 07|AA. Java References#SCG 07]\] Guideline 3-2 Define wrapper methods around modifiable internal state \[[Long 05|AA. Java References#Long 05]\] Section 2.2, Public Fields \[[Bloch 08|AA. Java References#Bloch 08]\] Items 13: Minimize the accessibility of classes and members; 14: In public classes, use accessor methods, not public fields |
06. Objects Orientation (OBJ) 06. Objects Orientation (OBJ) OBJ01-J. Understand how a superclass can affect a subclass