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.
Non-Compliant Code Example
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.
Compliant Solution
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 the invariant.
Risk Assessment
Not properly managing resources could lead to a denial-of-service attack.
Recommendation |
Severity |
Likelihood |
Remediation Cost |
Priority |
Level |
---|---|---|---|---|---|
OBJ00-A |
1 (low) |
1 (unlikely) |
2 (medium) |
P2 |
L3 |
References
We need some!