AlgoViz

Abstraction

easy 40 min

Show what a thing does, hide how it does it.

Video lesson · Chapter 1 of 6

Make a prediction

0:00 / 4:38

Abstraction

1:04Reel

Theory

Read or listen first. About 2 min.

What it is

Abstraction means keeping what matters for a purpose and leaving out the rest. A road map leaves out the trees. A List leaves out the arrays and the pointers.

In object-oriented code an abstraction is a set of operations with a promise: what each one does. The how is in a class behind it. The promise is called a contract, and languages write its outline as an interface, an abstract class or a protocol.

The slogan is: hide the how, show the what. The test is: can a caller use it correctly after reading only the contract?

Why it exists

Less to hold in the head. Nobody understands a million lines at once. With abstractions a person works on one level and trusts the level below.

Many insides. Coffee and tea machines, a disk and a cloud store: the caller does not change when the inside does.

Change is local. A faster grinder changes one class. The button stays.

Tests get simple. A fake with the same contract stands in for the slow real thing.

The price: one more thing to name and learn, and details that push through anyway when speed or failure matters. Those are called leaks.

A short history

  1. 1967

    Simula 67: a class declaration, presented by Dahl and Nygaard, describes a kind of object by its data and procedures.

  2. 1972

    David Parnas argues that a module should be described by what it hides, and not by the steps of a flow chart.

  3. 1974

    Barbara Liskov and Stephen Zilles publish Programming with Abstract Data Types: a type is defined by its operations, independent of how it is represented.

  4. 2002

    Joel Spolsky writes The Law of Leaky Abstractions: every non-trivial abstraction leaks to some degree.

  5. 2008

    Python 2.6 adds abstract base classes (PEP 3119). A class with an unfinished abstract method cannot be instantiated.

  6. 2014

    Java 8 allows default methods, so a published interface can grow without breaking its classes.

Words to know

Contract
What an operation needs, what it promises, how it fails, and what it does not promise.
Precondition
Must be true before the call. The caller's duty.
Postcondition
Is true after the call. The class's duty.
Abstract data type
A type known only by its operations and their meaning.
Interface
A list of operations without state. A class may promise several.
Abstract class
A half finished class: shared code plus gaps for subclasses. It cannot be instantiated.
Concrete class
A class with no gaps. Objects can be made of it.
Level of abstraction
The size of the words used. Make coffee, grind beans and turn the motor are three levels.
Leak
A hidden detail that a caller must know anyway.

The solution, twice

Reach the regular design first. Then go where a FAANG interviewer digs.

How it works

Step through the idea, or press Play.

Step 1 of 4

Hide. Which details may the caller forget?

Understand it

Start here

Three words are enough

Noor wants to drive a sledge through the snow. Watch what Noor has to know in each picture.

The sledge with three words
Paw 1! Paw 7! Paw 4!

The art is not to hide everything. It is to choose what stays on the card.

A car is the everyday example. You see a steering wheel, pedals and a dashboard. You do not see the engine, the gearbox or the hydraulics. Somebody swaps the engine for an electric motor, and you still drive with the same pedals.

The smell

A caller who grinds the beans

Below, the café knows every step of the machine. It forgot to heat the water the second time.

Python
class Machine:    def __init__(self):        self.hot, self.ground, self.log = False, False, []    def heat(self): self.hot = True; self.log.append("heat")    def grind(self): self.ground = True; self.log.append("grind")    def press(self):        self.log.append("coffee" if self.hot and self.ground else "cold brown water")        self.hot = self.ground = Falsem = Machine()m.heat(); m.grind(); m.press()        # the order is in the caller's headm.grind(); m.press()                  # forgot one stepprint(m.log)
Three public steps, and only one useful order. Every caller must know it.
Edit and run it in your browser

Callers know the steps

CoffeeParts+ heat()+ grind()+ press()TeaParts+ heat()+ steep()

1/2Parts, not drinks

The public methods are the steps of the machine. Nobody asked for steps, they asked for a drink.

depends on

Callers know one word

«abstract»BeverageMachine- log: list[str]+ make_beverage(): str# heat_water(celsius)

1/3The word

make_beverage is what callers want. It is abstract: the base class promises it and does not know how.

usesextends (is a)

How it works

One call, many levels

One word goes down the levels

Every arrow uses bigger words than the arrows below it. Nobody skips a level.

Four levels of one coffee

LevelWordsWho thinks hereMay change without the level above
3 GuestI want coffeeeveryonethe menu picture
2 Interfacemake_beverage()the programmer of the caféthe brand of machine
1 Implementationheat, grind, pressthe programmer of the machineorder and timing of steps
0 Hardwaremotor at 3,000 turns a minutethe engineerthe motor
A barista needs no motor speed. A guest needs no water temperature.

Contract

What belongs on the card

  • Meaning

    What is true after the call? Not: calls the grinder. But: returns one full cup.

  • Duties

    What must the caller bring? A cup in place, a name of 1 to 40 characters.

  • Failure

    Which errors, and what is the state afterwards?

  • Limits

    Size, time, threads: the few details that would surprise a caller.

  • Not promised

    The order of results, the exact text of a message. Saying so keeps you free.

Compilers check names and types. Meaning, failure and limits are checked by people and by tests. That is why a contract test that runs on every implementation is part of the abstraction and not an extra. A subclass that breaks the promise is the topic of Liskov substitution.

Tools

Interface or abstract class

Both write down a contract. The full comparison is on Interface vs abstract class. The short form:

Java

FeatureAbstract classInterface
Methods with a bodyyesyes: default, static and private methods
Instance variablesyesno, only constants
Constructorsyesno
How many per classone (extends)several (implements)
Access of membersanypublic, and private helpers since Java 9
Saysthis family shares codethis thing can do that

Abstract class when

  • The classes are one family
  • They share code or state
  • You need members that are not public
  • A constructor must set something up
  • Example: BeverageMachine with heat_water

Not an abstract class when

  • Unrelated classes need one ability: Flyable for a bird and a plane
  • A class needs several such abilities: a duck flies and swims
  • You only want a contract and loose coupling
  • Other teams will implement it
  • Then use an interface or protocol

Which tool writes this contract?

Python
from abc import ABC, abstractmethodfrom typing import Protocolclass Vehicle(ABC):                       # nominal: you must say that you are one    def __init__(self, brand): self.brand = brand    @abstractmethod    def start(self) -> str: ...    def label(self): return f"Brand: {self.brand}"class Car(Vehicle):    def start(self): return f"{self.brand} engine started"class Flyable(Protocol):                  # structural: having the method is enough    def fly(self) -> str: ...class Duck:                               # never mentions Flyable    def fly(self): return "duck flying"    def swim(self): return "duck swimming"def show(f: Flyable): return f.fly()print(Car("Toyota").start(), "|", Car("Toyota").label(), "|", show(Duck()))try:    Vehicle("none")except TypeError as e:    print("refused:", e)
An abstract base class refuses to be instantiated. A protocol asks only for the right methods, and a type checker verifies it.
Edit and run it in your browser

Other languages

The same idea with other words

LanguageContractAn unfinished class is refused
Javainterface, abstract classby the compiler
PythonABC with @abstractmethod, ProtocolABC: when you create the object
TypeScriptinterface, abstract classby the type checker, not at run time
JavaScriptby hand: new.target check, methods that throwonly when the check or method runs
C++pure virtual functions, virtual destructorby the compiler
Gointerface, fulfilled without a wordby the compiler at the assignment
In C++ a class with at least one pure virtual function is abstract. Without a virtual destructor, deleting through the base pointer is undefined behaviour.

Limits

Leaks and wrong levels

A remote file that looks like a local one is a fine abstraction, until the network is gone and read takes ten seconds. The slow network was hidden and now decides everything. You cannot close every leak. You can choose: write it into the contract (a timeout, an error), or make the caller ask for it (prefetch()).

Users may upload a photo. Tomorrow it goes to a disk, next year to a cloud store. What does the code call?

BreaksThe cloud SDK everywhere
How
Each feature builds a request with bucket, region and ACL.
Limit
The second store means a change in every feature, and tests need the network.
Choose when
A throwaway script.
WorksA thin wrapper with the same words
How
putObject(bucket, key, acl, bytes) behind an interface.
Limit
The words belong to one vendor. A disk has no ACL.
Choose when
One vendor for sure, only tests need a fake.
StrongA contract in our words
How
save(photo_id, bytes) and open(photo_id), with size limit and errors written down.
Limit
Special vendor features need a decision each time.
Choose when
The default when the rest of the code thinks in photos.

A contract grows up

An abstraction may also go away. That is not a failure.

Neighbours

Abstraction and the other pillars

Encapsulation builds the wall, abstraction chooses the windows. Polymorphism is what makes one call reach many insides. Inheritance is one way to build the insides, and not the only one. Dependency inversion tells you who should own the contract: the caller.

Mistakes

Five common mistakes

  • An interface for every class. One class, one interface, same methods: two files and no new idea. Wait for a second inside or a real test need.
  • Names from the inside. writeToS3 cannot be kept by a disk. Name the purpose.
  • A flag for each special case. make(type, withMilk, decaf, ...): the caller knows the inside again.
  • A method some insides cannot do. They throw. Split the contract, see Interface segregation.
  • Too general too early. A framework for one case. See YAGNI.

Summary

The whole topic in one minute.

Abstraction keeps what matters for a caller and hides the rest behind a small contract. Different classes fulfil the contract in their own way, so callers stay simple and insides can be replaced.

Write the contract in the caller's words, with failure and limits. Use an interface for an ability and an abstract class for a family that shares code. Test every inside against the same contract, and remove abstractions that stopped paying.

  • Show what, hide how, and choose what the caller must still know.
  • A contract has meaning, duties, failure, limits, and things not promised.
  • Name it in the caller's words, not after the first inside.
  • Interface for an ability, abstract class for a family with shared code.
  • Work on one level at a time.
  • Every abstraction leaks a little. Put the important leak on the card.

Sources