...
Noncompliant Code Example (Public Final Array)
A nonzero-length array is always mutable. Declaring a public final array is a potential security risk as the array elements may be modified by a client.
Code Block | ||
---|---|---|
| ||
public final SomeType [] SOMETHINGSstatic final String[] items = {/* ... */}; |
Declaring the array reference final prevents modification of the reference but does not prevent clients from modifying the contents of the array.
Compliant Solution (Index Getter)
This compliant solution declares a public array and provides public methods to get individual items and array size.
Code Block | ||
---|---|---|
| ||
private static final String[] items = {/* ... */}; public static final String getItem(int index) { return items[index]; } public static final int getItemCount() { return items.length; } |
Providing direct access to the array objects themselves is safe because String
is immutable.
Compliant Solution (
...
Clone the Array)
This compliant solution declares the array defines a private
array and provides a public
accessor method that returns a copy of the array:
Code Block | ||
---|---|---|
| ||
private static final SomeType String[] SOMETHINGSitems = {/* ... */}; public static final SomeType String[] somethingsgetItems() { return SOMETHINGSitems.clone(); } |
Because a copy of the array is returned, the original array values cannot be modified by a client. Note that a manual deep copy could be required when dealing with arrays of objects. This generally happens when the objects do not export a clone()
method. Refer to OBJ06-J. Defensively copy mutable inputs and mutable internal components for more information.
As before, this method provides direct access to the array objects themselves, but this is safe because String
is immutable. If the array contained mutable objects, the getItems()
method could return an array of cloned objects insteadThis approach prevents the elements of the class instance of the array from being modified by a client.
Compliant Solution (
...
Unmodifiable Wrappers)
This compliant solution declares An alternative approach is to have a private
array from which a public
immutable list is contructedconstructed:
Code Block | ||
---|---|---|
| ||
private static final SomeType String[] THE_THINGSitems = { ... }; public static final List<SomeType>List<String> SOMETHINGSitemsList = Collections.unmodifiableList(Arrays.asList(THE_THINGSitems)); |
Neither the class instance field original array values nor the public
list can be modified by a client. For more details about unmodifiable wrappers, refer to OBJ56-J. Provide sensitive mutable classes with unmodifiable wrappers. This solution can also be used when the array contains mutable objects.
Exceptions
OBJ01-EX0: Fields with no associated behavior or invariants can be public. According to Sun's Code Conventions document [Conventions 2009]:
...