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

Compare with Current View Page History

« Previous Version 33 Next »

Do not expose references to mutable objects to client code. Never initialize such a field to a client-provided object reference or return the object reference from an accessor. Exposing a public static final object allows clients to modify the contents of the object (although they will not be able to change the object itself, as it is final). 

Noncompliant Code Example

public static final SomeType [] SOMETHINGS = { ... };

With this declaration, SOMETHINGS[1], etc. can be modified by clients of the code.

This noncompliant code example also violates OBJ01-J. Limit accessibility of fields.

Compliant Solution

One approach is to have a private array and a public method that returns a copy of the array:

private static final SomeType [] SOMETHINGS = { ... };
public static final SomeType [] somethings() {
  return SOMETHINGS.clone();
}

Now, the original array values cannot be modified by a client.

Compliant Solution 2

An alternative approach is to have a private array from which a public immutable list is constructed:

private static final SomeType [] THE_THINGS = { ... };
public static final List<SomeType> SOMETHINGS =
  Collections.unmodifiableList(Arrays.asList(THE_THINGS));

Now, neither the original array values nor the public list can be modified by a client.

Risk Assessment

Having a public static final array is a potential security risk because the array elements may be modified by a client.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

OBJ13-J

Medium

Likely

Low

P18

L1

Automated Detection

ToolVersionCheckerDescription
SonarQube Java Plugin
Unable to render {include} The included page could not be found.
S2386, S2384Implemented

Related Vulnerabilities

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

References

[Bloch 2008]Item 13, "Minimize the Accessibility of Classes and Members"
[JLS 2015]§6.6, "Access Control"

 


 

  • No labels