Comparison
Defensive copyvsImmutability
Defensive copy
you handed the object a list, changed your list afterwards, and the object's state changed with it.
Copying a mutable argument on the way in, or a mutable field on the way out, so a caller cannot reach past the interface and change your state. It is the price of encapsulation in a language with mutable collections and shared references. The alternative that removes the need entirely is immutability, which is one of the strongest practical arguments for it.
Full entry →Immutability
nothing that was handed out can be changed, so you stopped copying defensively and stopped worrying about who else holds it.
Building values that cannot change after construction, so a change produces a new value instead. It removes aliasing bugs, makes equality and hashing safe, makes objects shareable across threads without locks, and makes change detection a reference comparison. The costs are allocation and awkwardness in the places where a large structure genuinely does change often, which is what persistent data structures address.
Full entry →