Abstraction
easy 40 minShow what a thing does, hide how it does it.
Video lesson · Chapter 1 of 6
Make a prediction
See it run
Watch what the caller has to know, and what it may forget.
Operations
A caller with all the steps
The café heats, grinds and presses by itself.
Step 1 of 5
Heat
Step one is in the caller's head.
Step 1: Heat
m.heat()m.grind()m.press()m.grind() # second cupm.press() # forgot to heat- Good for
- One caller, one day
- Costs
- Every caller owns the recipe
If there is one useful order, why can the caller choose?
In the real world
The same abstraction doing real jobs. Pick one and step through it.
Pedals in front, an engine behind, then a motor.
Step 1 of 4
Press go
The driver presses one pedal.
Step 1: Press go
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Steps as the interface
criticalEvery caller must know the only useful order.
Wrongm.heat(); m.grind(); m.press()Rightm.make_beverage()Vendor words
majorThe second inside cannot keep them.
Wrongstore.put_object(bucket, key, acl, data)Rightphotos.save(photo_id, data)An interface per class
minorTwo files, the same methods, nothing hidden.
Wrongclass IUserService: ... # one implementation, no fakeRightclass UserService: ...A method some refuse
majorCallers cannot trust the type.
Wrongclass Penguin(Bird): def fly(self): raise NotImplementedErrorRightclass Penguin: def swim(self): ...Flags
majorThe caller chooses code inside again, and combinations explode.
Wrongmake("tea", True, False, True)Rightchildren_menu.tea()No virtual destructor in C++
criticalDeleting through the base pointer is undefined behaviour.
Wrongclass Base { virtual void f() = 0; };Rightvirtual ~Base() = default;
Interview tips
Find the word
- What does the caller want?
- One verb, caller's language
- Then the steps go inside
Write the card
- Meaning and duties
- Errors and limits
- What is not promised
Prove it
- A second inside, even a fake
- One contract test
- Delay and failure injected
Know when not
- One class, no second in sight
- Only two examples
- A layer that only forwards