Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: added text about arrays of mutable objects

...

This compliant solution makes the array private, and provides a public methods to get individual items and array size. Providing direct access to the array objects themselves is safe because String is immutable.

Code Block
bgColor#ccccff
private static final String[] items = {/* ... */};

public static final String getItem(int index) {
  return items[index];
}

public static final int getItemCount() {
  return items.length;
}

...

Consequently, 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 guideline FIO00-J. Defensively copy mutable inputs and mutable internal components for more information.

As before, this method provides direct access to the array objects themselves, which is safe because String is immutable. If the array contained mutable objects, the getItems() method could return a cloned array of cloned objects.

Compliant Solution (Unmodifiable Wrappers)

...

Neither the original array values nor the public list can be modified by a client. For more details about unmodifiable wrappers, refer to guideline SEC14-J. Provide sensitive mutable classes with unmodifiable wrappers. This solution would still be useful if the array contained mutable items instead of String.

Risk Assessment

Incorrectly assuming that final references cause the contents of the referenced object to remain mutable can result in an attacker modifying an object thought by the programmer to be immutable.

...