Potential security hole- Final field containing a reference to a mutable object

Potential security hole- Final field containing a reference to a mutable object

As a thumb rule, instance fields should never be public. If an instance field is non-final, or is a final reference to a mutable object, then by making the field public, we give up the ability to limit the values that can be stored in the field. So classes with public mutable fields are not thread-safe.

Developers love constants, they expose constants via public static final fields. By convention, such fields have names consisting of capital letters, with words separated by underscores. It is critical that these fields contain either primitive values or references to immutable objects. A final field containing a reference to a mutable object has all the disadvantages of a non-final field, and since we used public access modifier so it can give disastrous results.

Note that a nonzero-length array is always mutable, so it is wrong for a class to have a public static final array field. If a class has such a field, clients will be able to modify the contents
of the array. This is a frequent source of security holes:

// Potential security hole!
public static final Thing[] VALUES = { ... };

There are two ways to fix the problem.

1. To combat this, the visibility of the array field can be restricted to private or package private. Alternatively, and often better, is to do away with the array together and use a ‘List’, or other appropriate collection type. By using a collection, you control if updates are allowed, since all updates go through methods. You can prevent updates by wrapping your collection using Collections.unmodifiableList()

private static final Thing[] PRIVATE_VALUES = { ... };
public static final List VALUES =
Collections.unmodifiableList(Arrays.asList(PRIVATE_VALUES));

2. Alternatively, you can make the array private and add a public method that returns a copy of a private array:

private static final Thing[] PRIVATE_VALUES = { ... };
public static final Thing[] values() {
  return PRIVATE_VALUES.clone();
}

Leave a Reply

Your email address will not be published. Required fields are marked *