← 返回首页
Exposing internal representation — CodeQL query help documentation CodeQL docs
CodeQL documentation
CodeQL resources

Exposing internal representation

ID: java/internal-representation-exposure Kind: problem Security severity: Severity: recommendation Precision: high Tags: - quality - reliability - correctness - modularity - external/cwe/cwe-485 Query suites: - java-code-quality.qls - java-security-and-quality.qls

Click to see the query in the CodeQL repository

A subtle type of defect is caused when an object accidentally exposes its internal representation to the code outside the object, and the internal representation is then (deliberately or accidentally) modified in ways that the object is not prepared to handle. Most commonly, this happens when a getter returns a direct reference to a mutable field within the object, or a setter just assigns a mutable argument to its field.

Recommendation

There are three ways of addressing this problem:

Example

In the following example, the private field items is returned directly by the getter getItems. Thus, a caller obtains a reference to internal object state and can manipulate the collection of items in the cart. In the example, each of the carts is emptied when countItems is called.

public class Cart { private Set<Item> items; // ... // AVOID: Exposes representation public Set<Item> getItems() { return items; } } .... int countItems(Set<Cart> carts) { int result = 0; for (Cart cart : carts) { Set<Item> items = cart.getItems(); result += items.size(); items.clear(); // AVOID: Changes internal representation } return result; }

The solution is for getItems to return a copy of the actual field, for example return new HashSet<Item>(items);.

References