liveBook · Manning

Untrusted code

As explained in Grokking Simplicity

Program code whose behavior or data-modification effects cannot be assumed to follow the calling system's safety or immutability rules.

Untrusted code is code whose behavior and data-modification effects cannot be assumed to follow your immutability discipline. Treat legacy systems, libraries, and large routines as outside your safe zone whenever they may mutate data or retain references to it. section 7.2 section 7.0

Protect immutable data at every boundary:

  • Copy as data leaves trusted code: make a deep copy, then pass the copy to untrusted code. section 7.5
  • Copy as data enters trusted code: immediately deep-copy incoming data and use only the copy. section 7.5
  • Use deep copies when the other code may modify any nested structure; shallow copies can still share mutable structure. section 7.9
  • Do not rely on copy-on-write unless the called code follows the same discipline and its modifications are known. section 7.11 section 7.2

Wrapping an unsafe promotion routine

Keep the safe zone intact by copying before and after the call: function black_friday_promotion_safe(cart) { var cartCopy = deepCopy(cart); black_friday_promotion(cartCopy); return deepCopy(cartCopy); } The first copy protects the original; the second prevents modified results from re-entering trusted code. section 7.6

Image

Use the safe-zone diagram to trace where data crosses into untrusted code and where defensive copies are required. section 7.2

How Grokking Simplicity covers it

How deep it goes
Defines the boundary problem, gives two defensive-copying rules, compares copy costs, and demonstrates wrappers.
Examples
Uses Black Friday promotion, payroll calculation, and shared user-update data to illustrate unsafe boundaries.
What it assumes
Assumes copy-on-write and immutability, while defining deep copies, shallow copies, and defensive copying.
What you can do after
Apply defensive copying to wrap unsafe calls and protect data entering or leaving immutable code.
How it connects
Connects immutability with defensive copying, copy-on-write, deep copying, shallow copying, and legacy code.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Grokking Simplicity. The section links point to the parts of the book it draws on.