Abstraction
easy 40 minShow what a thing does, hide how it does it.
Video lesson · Chapter 1 of 6
Make a prediction
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
1967
Simula 67: a class declaration, presented by Dahl and Nygaard, describes a kind of object by its data and procedures.
1972
David Parnas argues that a module should be described by what it hides, and not by the steps of a flow chart.
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.
2002
Joel Spolsky writes The Law of Leaky Abstractions: every non-trivial abstraction leaks to some degree.
2008
Python 2.6 adds abstract base classes (PEP 3119). A class with an unfinished abstract method cannot be instantiated.
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.
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 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.
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)Callers know the steps
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
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
Four levels of one coffee
| Level | Words | Who thinks here | May change without the level above |
|---|---|---|---|
| 3 Guest | I want coffee | everyone | the menu picture |
| 2 Interface | make_beverage() | the programmer of the café | the brand of machine |
| 1 Implementation | heat, grind, press | the programmer of the machine | order and timing of steps |
| 0 Hardware | motor at 3,000 turns a minute | the engineer | the motor |
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
| Feature | Abstract class | Interface |
|---|---|---|
| Methods with a body | yes | yes: default, static and private methods |
| Instance variables | yes | no, only constants |
| Constructors | yes | no |
| How many per class | one (extends) | several (implements) |
| Access of members | any | public, and private helpers since Java 9 |
| Says | this family shares code | this 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:
BeverageMachinewithheat_water
Not an abstract class when
- Unrelated classes need one ability:
Flyablefor 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?
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)Other languages
The same idea with other words
| Language | Contract | An unfinished class is refused |
|---|---|---|
| Java | interface, abstract class | by the compiler |
| Python | ABC with @abstractmethod, Protocol | ABC: when you create the object |
| TypeScript | interface, abstract class | by the type checker, not at run time |
| JavaScript | by hand: new.target check, methods that throw | only when the check or method runs |
| C++ | pure virtual functions, virtual destructor | by the compiler |
| Go | interface, fulfilled without a word | by the compiler at the assignment |
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)andopen(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
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.
writeToS3cannot 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
- Liskov and Zilles, Programming with Abstract Data Types (1974)
- Linux kernel: overview of the virtual file system
- RFC 9293: Transmission Control Protocol
- Python: abc, abstract base classes
- Java 21 API: List
- Java 21 API: RandomAccess
- Go: package io
- PostgreSQL: index access method interface
- Kubernetes: container runtime interface
- SLF4J manual
- Joel Spolsky, The Law of Leaky Abstractions (2002)
- Sandi Metz, The Wrong Abstraction (2016)