Item 39: Make defensive copies when needed
1. You must program defensively, with the assumption that clients of your class will do their best to destroy its invariants.
2. For immutable class, it is essential to make a defensive copy of each mutable parameter to the constructor and to use the copies as components.
3. Defensive copies should be made before checking the validity of the parameters, and the validity check is performed on the copies rather than on the originals. It protects the class against changes to the parameters from another thread during the “window of vulnerability” between the time the parameters are checked and the time they are copied which is known as a time-of-check/time-of-use or TOCTOU attack.
4. Do not use the clone method to make a defensive copy of a parameter whose type is subclassable by untrusted parties. For example, Date is nonfinal, the clone method is not guaranteed to return an object whose class is java.util.Date: it could return an instance of an untrusted subclass specifically designed for malicious mischief. Such a subclass could, for example, record a reference to each instance in a private static list at the time of its creation and allow the attacker to access this list. This would give the attacker free reign over all instances.
5. For immutable class, modify the accessors to return defensive copies of mutable internal fields
6. If you are considering using a client-provided object reference as an element in an internal Set instance or as a key in an internal Map instance, you should be aware that the invariants of the set or map would be destroyed if the object were modified after it is inserted.
7. Nonzero-length arrays are always mutable. Therefore, you should always make a defensive copy of an internal array before returning it to a client. Alternatively, you could return an immutable view of the array.
8. You should, where possible, use immutable objects as components of your objects, so that you that don’t have to worry about defensive copying.
9. If the cost of the copy would be prohibitive and the class trusts its clients not to modify the components inappropriately, then the defensive copy may be replaced by documentation outlining the client’s responsibility not to modify the affected components.