Comparison
Deep copy vs shallow copyvsDefensive copy
Deep copy vs shallow copy
you copied the object, edited the copy's list, and the original's list changed too.
A shallow copy duplicates the object and shares whatever its fields point at; a deep copy duplicates the reachable graph as well. Almost every default copy in every language is shallow, which is why the surprise is so common. Deep copies are expensive, must decide what to do about cycles and shared identity, and are usually a sign that immutable values would serve better.
Full entry →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 →