sicp.io
2.1.1 · Abstraction barriers

Build with an interface, not a representation.

Constructors and selectors let a program use rational numbers without spreading knowledge of their pair representation through every operation.

Guiding question

What does an abstraction barrier protect us from changing?

  • Separate an abstract value from its representation
  • Use constructors and selectors as the only boundary
  • Recognize code that reaches through an abstraction

make-rat constructs a rational value. numer and denom select its parts. add-rat depends on those three operations, not on car, cdr, or the order in which the pair stores its fields.

The pair is useful machinery, while the public idea is the interface. Keeping representation knowledge behind a stable interface makes later changes local instead of contagious.

SICP code346 of 1,048,576 UTF-8 bytes
Examples
Result
Output
Value
Diagnostic
Execution trace0 / 0 events
    Programs run in the browser with their result and execution trace.
    Expected result

    The first program returns the exact rational value 5/6.

    Trace focus

    Follow calls to make-rat, numer, and denom. add-rat never needs a direct pair operation, so its process does not reveal the storage order.

    Try it yourself

    Change the program and compare the result.

    Store the denominator first in make-rat. Change only numer and denom, then confirm that add-rat still returns 5/6.

    Show hint

    If add-rat must change, some representation knowledge crossed the intended boundary.

    Complete this lesson

    0 of 20 lessons complete in this chapter0%