Abstraction
Hide complexity behind clear contracts and essential interfaces.
16 minLevel 11 of 20
What abstraction means
Abstraction shows the essential and hides the rest. A PaymentGateway.charge() hides Stripe SDK details. Nest controllers talk to services, not SQL.
Essential API
interface PaymentGateway {
charge(amount: number): string;
}
class StripeGateway implements PaymentGateway {
charge(amount: number) {
// pretend SDK complexity lives here
return `charged ${amount} via Stripe`;
}
}
class Checkout {
constructor(private gateway: PaymentGateway) {}
pay(amount: number) { return this.gateway.charge(amount); }
}
console.log(new Checkout(new StripeGateway()).pay(42));Levels of abstraction
Good systems have clear layers: HTTP → application → domain → infrastructure. Each layer abstracts the one below. Crossing layers carelessly creates spaghetti.
Layered call
class OrderRepo { insert(id: string) { return "db:" + id; } }
class OrderService {
constructor(private repo: OrderRepo) {}
create(id: string) { return this.repo.insert(id); }
}
class OrderController {
constructor(private orders: OrderService) {}
post(id: string) { return this.orders.create(id); }
}
console.log(new OrderController(new OrderService(new OrderRepo())).post("o1"));Abstract without over-abstracting
Abstractions must earn their keep. One implementation forever? A plain class may be enough. Introduce interfaces at boundaries you expect to vary (DB, mail, payment).
Boundary interface
interface Mailer { send(to: string): void; }
class ConsoleMailer implements Mailer {
send(to: string) { console.log("mail→", to); }
}
class Signup {
constructor(private mailer: Mailer) {}
run(email: string) { this.mailer.send(email); }
}
new Signup(new ConsoleMailer()).run("a@b.c");Check your understanding
5 questionsQuestion 1 of 5
Score: 0
Multiple choice