Warning. Encapsulation and defensive copying

[comp1110-47]

Encapsulation means that the internal state of an object can only be changed through its defined methods. This is broken if a method returns a direct reference to an internal array or other mutable object, because the caller can then modify it from outside.

The fix is to return instead a defensive copy: a fresh object with the same contents. The caller is then free to do whatever they like with the copy without affecting the internal state of the object.

bars magnifying-glass caret-down plus minus arrow-right xmark