AlgoViz

Ensuring proper encapsulation

medium 40 min

Private fields are the start, not the end.

Watch lesson4:46

Where it shows up

The same pattern appears across everyday software.

  • Java `List.copyOf`

    The documentation says a later change of the given collection is not reflected in the result, and that an unmodifiable List is generally not copied again.

  • Java `Collections.unmodifiableList`

    Returns an unmodifiable view. Writing through it fails, and changes of the list behind it are visible.

  • Java secure coding guidelines

    Guideline 6-2: create copies of mutable output values. The input section says validation must come after defensive copying.

  • Java module system, JEP 403

    Since Java 17 internals of the JDK are strongly encapsulated. Code that used them by reflection has to use the supported API.

  • JavaScript private elements

    MDN: the privacy of `#` members is enforced by JavaScript itself. Reading one outside the class is a syntax error.

  • Python `MappingProxyType`

    The standard library offers a read only proxy of a mapping with a dynamic view: later changes of the mapping show through.

  • PEP 8 underscore

    Describes one leading underscore as a weak internal use indicator. `from M import *` skips such names.

  • C++ Core Guidelines

    C.2: use a class if there is an invariant, a struct if members can vary independently. C.9: minimize exposure of members.

  • CopyOnWriteArrayList

    Every change makes a fresh copy of the array, so iterating readers need no lock and never see a half change.