If data members are declared public
or protected
, it is difficult to control how they are accessed. It is possible that they could can be manipulated in unintented unintended ways, with undefined consequences. Better is to declare all data members private and define accessor functions that control their uses to those intended. Also, 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). Public modifier functions should preserve any Methods that are declared public
or protected
must preserve the invariants of the typeclass 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.
Code Block | ||
---|---|---|
| ||
public class Widget { public int total; // ... void add (someTypeSomeType someParameterssomeParameter) { // ... total++; // ... } void remove (someTypeSomeType someParameterssomeParameter) { // ... 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
Compliant Solution
This compliant solution declares total
as private
and provides a public
accessor. The method add()
modifies its value without violating class invariants.
Code Block | ||
---|---|---|
| ||
public class Widget { private int total; // ... void add (someType someParameterssomeParameter) { // ... total++; // ... } void remove (someType someParameterssomeParameter) { // ... total--; // ... } // ... public int getTotal () { return total; } // ... } |
Now, total
is private, and the functions that modify its value preserve any class invariants.
Risk Assessment
Not properly managing resources could lead to an attacker causing unintended behaviorFailing to declare data members private
can break encapsulation.
Recommendation | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
OBJ00- J | medium | likely | medium | P12 | L1 |
...