Grade 9 Computer Science · Abstraction

What a good abstraction hides

The distinction between what may be hidden and what must stay visible.

An internal detail you must tell

A function sorts a list and returns it sorted. Does whoever calls it need to know that it also rearranged the list it received? That sounds like an implementation detail, fine to hide — and it is exactly from details like that that bugs are born which appear far from their cause.

It is easy to conclude from the previous lesson that all hiding is good. That is not so: there are things whose hiding makes the abstraction dangerous, and things whose hiding is the whole benefit. The distinction between them is all that remains to learn here.

WhatHide or reveal
Which algorithm is usedHide
The order of magnitude of the costReveal
Whether the input is changedReveal
What happens on failureReveal
def sort_names(names):
    """Return a new sorted list. Cost grows a little
    faster than the length. The input is not changed.
    Raises ValueError if any item is not a string.
    """
    ...

Why cost must be visible

This is the point easiest to miss. A function that looks cheap and in fact passes over all the data will lead whoever uses it to write it inside a loop — and, without knowing, to build a quadratic algorithm. They did nothing wrong; the abstraction hid from them exactly what they needed to know. So the order of magnitude of the cost is part of the promise and not an internal detail, and that is one reason the unit on efficiency comes before this one.

Example 1 — a hidden cost

  1. The function looks like one operation.
  2. In fact it passes over all the data.
  3. The user writes it inside a loop.
  4. And built a quadratic algorithm without knowing.

Example 2 — a hidden change to the input

  1. The function sorts the list it received.
  2. The caller keeps using that same list.
  3. Its order changed beneath them.
  4. And the bug will appear far from the cause.
Sorting: Before writing the documentation: what do you hide, and what must you tell the user? — 7 items into 2 groups (Hide, Reveal), with a check and a reason for each item.