liveBook · Manning

Defensive copy

As explained in Data-Oriented Programming in Java

A defensive copy is an independently created duplicate of mutable data that prevents external mutation from changing the original representation.

A defensive copy is an independently created duplicate of mutable data that prevents external mutation from changing the original representation. In a validated cart, copying the active and saved collections makes the immutable data safe after construction. section 9.3.1

Copy collections at the boundary

A ValidCart validates each item, then assigns active = List.copyOf(active) and saved = List.copyOf(saved). The cart therefore cannot be corrupted through later mutation of the input lists.

How Data-Oriented Programming in Java covers it

How deep it goes
Demonstrates collection copying in code, but does not develop a broader catalogue of defensive-copy techniques.
Examples
Uses active and saved cart lists copied with List.copyOf after invariant validation.
What it assumes
Assumes familiarity with Java collections, records, constructors, and mutable versus immutable data.
What you can do after
Apply defensive copying when constructing immutable validated data from mutable collections.
How it connects
Connects defensive copies with immutability, invariants, records, lists, sets, and maps.

Also explained in

Compare how 2 books explain defensive copy →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Data-Oriented Programming in Java. The section links point to the parts of the book it draws on.