Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Added more clarification about importance of SomeType immutability.

...

Code Block
bgColor#FFCCCC
public static final SomeType [] SOMETHINGS = { ... };

This Even though SomeType is immutable, this declaration allows the SOMETHINGS array to be modified by untrusted clients of the code. Any element of the array can be assigned a new SomeType object, which would effectively assign a new value to that array element.

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

...

This noncompliant code example complies with OBJ01-J. Limit accessibility of fields by declaring the array private.

Suppose that SomeType is immutable.

Code Block
bgColor#FFCCCC
private static final SomeType [] SOMETHINGS = { ... };
public static final getSomethings() {return SOMETHINGS;} 

HoweverEven though SomeType is immutable, the public getter method enables untrusted clients to modify the SOMETHINGS array. Any element of the array can be assigned a new SomeType object, which would effectively assign a new value to that array element.

Compliant Solution (clone)

One Continuing with the assumption that SomeType is immutable, one approach is to have a private array and a public method that returns a copy of the array:

...

Now, the original array cannot be modified by any client.  If SomeType were mutable, this approach would not be effective because the array clone references the same SomeType objects as the SOMETHINGS array. If the client changed the clone SomeType objects directly, the SomeType objects referenced by the SOMETHINGS array would also change.

Compliant Solution (Unmodifiable List)

An Continuing with the assumption that SomeType is immutable, an alternative approach is to have a private array from which a public immutable list is constructed:

...

Now, neither the original array values nor the public list can be modified by a client. If SomeType were mutable, this would not be effective because the list references the same SomeType objects as the SOMETHINGS array. The unmodifiabileList prevents the list from being modified, not the elements in the list. If the client modified the list's SomeType objects directly, the SomeType objects referenced by the SOMETHINGS array would also change.

Risk Assessment

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

...