Loading
Loading
Object-Oriented Foundations
Hiding state is the easy half. Hiding decisions is the half that matters.
By the end of this chapter
Make fields private, expose getters and setters. This is real and worth doing, but on its own it achieves very little: a class with a private field and a public getter and setter for it has exactly the same coupling surface as a public field, plus more code.
The useful form of encapsulation hides a decision, not a variable. Consider an order that knows its items and a caller that wants the total.
| Design | The caller must know |
|---|---|
| `order.getItems()` and sum them | How totals are computed, that discounts exist, tax rules |
| `order.total()` | Nothing |
In the first design, every caller that wants a total re-implements the rule, and they drift. When a discount is introduced, you find them by grepping and hoping. In the second, the rule has one home.
An abstraction is good when it can be described entirely in the caller's vocabulary. "A PaymentGateway charges an amount to a customer and tells you whether it worked" describes a seam. "A StripeClientWrapper exposes the Stripe charge endpoint" describes an implementation with an interface drawn around it — and it will leak Stripe's concepts into everything that touches it.
Sign in to keep a note here. It is free, and nobody else can see it.
Sign inWhat this chapter was for: