Lesson 1 · Unit 03
Adapter and facade
Make their interface look like yours
What you practise
- Wrap a library so your code sees your interface
- One simple front door over a messy subsystem
- Swapping the vendor
Try a question from this lesson
Pick one
Forty files call send(to, text) on OldSms. The company moves to NewSms. What is the cheapest safe change?
class OldSms:
def send(self, to, text):
return "old " + to
class NewSms:
def push(self, msg):
return "new " + msg["dest"]class OldSms {
send(to, text) {
return "old " + to;
}
}
class NewSms {
push(msg) {
return "new " + msg.dest;
}
}class OldSms {
send(to: string, text: string) {
return "old " + to;
}
}
type Msg = { dest: string; body: string };
class NewSms {
push(msg: Msg) {
return "new " + msg.dest;
}
}Correct answer
Write one class with send(to, text) that calls push inside
Why
One small class can offer the old shape and translate to the new one. Forty edits are forty chances for a mistake, and the vendor's library is not yours to rename: the next update would undo it.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Adapter
An adapter wraps an object whose interface you cannot change and offers the interface your code expects.
Inside, it translates: argument order, names, units. Outside, nobody can tell that the vendor changed. Everything known about the vendor lives in this one class.
class Adapter:
def __init__(self, vendor):
self.vendor = vendor
def send(self, to, text):
msg = {"dest": to, "body": text}
return self.vendor.push(msg)class Adapter {
constructor(vendor) {
this.vendor = vendor;
}
send(to, text) {
const msg = { dest: to, body: text };
return this.vendor.push(msg);
}
}class Adapter {
constructor(private vendor: NewSms) {}
send(to: string, text: string) {
const msg = { dest: to, body: text };
return this.vendor.push(msg);
}
}TypeScript noteThe object literal is checked against the Msg type that push expects: a misspelt dest would not compile.
Concept
Facade
A facade is one simple entry point in front of several parts that have to be used together, in the right order.
It does not add features. It removes the need to know the parts: most callers want "back up the database", not the four steps that make one.
8 more exercises in the app
- 2× type the answer
- 1× fill the blanks
- 1× true or false
- 1× order the lines
- 2× multiple choice
- 1× match the pairs
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.