Notes
The problem
Here is a checkout that ships parcels. It knows the road courier's fee formula, its hill area surcharge and how it builds tracking ids. It also knows the air courier's fuel fee and flight slots. Adding a third courier means editing checkout again. Changing one fee rule means retesting all of checkout. And you cannot test checkout without the real courier logic running inside it.
if (mode.equals("road")) {
double fee = 40 + kg * 12;
if (pin.startsWith("19")) fee += 60;
id = "RD-" + hubFor(pin) + "-" + seq++;
} else if (mode.equals("air")) {
double fee = 150 + kg * 55 + fuel();
id = "AIR" + flightSlot() + seq++;
}
// new courier: edit and retest checkout The idea
Abstraction means giving callers a simple view of what something does and hiding how it does it. What does checkout really need from a courier? Only two things. How much will this parcel cost? And please ship it and give me a tracking id. Fee formulas, hubs, flight slots and fuel prices are details. Abstraction draws a line between those two questions and everything else.
- abstraction: give callers a
- simple view of WHAT an
- object does and hide HOW
- checkout needs two answers:
- how much will it cost?
- ship it, give me an id
- everything else is detail
The contract
In Java we write the what as an interface. The Courier interface has three methods: a name, a quote for a parcel in rupees, and ship, which returns a tracking id. A parcel is a small record with its weight and pincode. Notice what is missing: no fee formula, no hub, no flight slot. The interface is a contract that any courier can sign, however it works inside.
interface Courier {
String name();
long quote(Parcel p); // in rupees
String ship(Parcel p); // tracking id
}
record Parcel(double kg, String pincode)
no fields, no formulas, no hubs The hidden how
Each courier implements the contract in its own way. Road courier keeps its base fee, its per kilo rate and its hill area surcharge private. Air courier has its own fuel fee and flight slots. These details now live in one class each. If the road courier changes its hill surcharge, only one class changes, and checkout does not even need to be recompiled.
class RoadCourier implements Courier {
public long quote(Parcel p) {
long fee = 40 + Math.round(p.kg() * 12);
return isHill(p) ? fee + 60 : fee;
}
public String ship(Parcel p) {
return "RD-" + hubFor(p) + "-" + ++seq;
}
private boolean isHill(Parcel p) {..}
} The caller
Now checkout receives a list of couriers and only talks through the interface. To send a parcel, it asks each courier for a quote, picks the cheapest, and calls ship. The words road and air do not appear anywhere in checkout. A new courier is a new class plus one line where the list is built. Checkout itself never changes.
Checkout(List<Courier> couriers) {..}
String send(Parcel p) {
Courier best = cheapest(p);
return best.ship(p);
}
// no "road", no "air", no formulas Run-through
Trace one order. A two kilo parcel to Pune. Checkout asks the road courier for a quote and gets sixty four rupees. It asks the air courier and gets two hundred and eighty. It picks road and calls ship, and gets back a tracking id. Checkout made three calls through one interface and never learned how either courier works inside.
Testing
A big reward of abstraction is testing. Because checkout only knows the Courier interface, a test can hand it a fake courier that returns a fixed quote and simply records what it shipped. No network, no fee tables, and the test runs in milliseconds. If you cannot easily write a fake for something, that is a hint the abstraction is missing or leaking.
class FakeCourier implements Courier {
final List<Parcel> shipped = ..;
public long quote(Parcel p) {
return 10;
}
public String ship(Parcel p) {
shipped.add(p);
return "FAKE-" + shipped.size();
}
} Levels of abstraction
Abstraction also works inside a single method. A method should stay at one level of detail. If place order validates the cart, and then suddenly builds a SQL string by hand, the reader keeps jumping between business steps and low level plumbing. Keep the top method as a short story of steps, validate, reserve stock, send, notify, and push each detail down into its own method or class.
// mixed levels: hard to read
placeOrder() {
validate(cart);
String sql = "INSERT INTO orders...";
...
}
// one level: reads like a story
placeOrder() {
validate(cart); reserveStock(cart);
String id = checkout.send(parcel);
notifyBuyer(id); } Abstract types
Java gives you two tools for abstraction. An interface describes only the contract, with optional default methods. An abstract class can describe the contract and also share some code and fields between implementations, but you cannot create one with new. Both let callers depend on what, not how. Lesson six compares them in detail, including how to choose between them.
- interface: only the contract
- (plus optional defaults)
- abstract class: contract plus
- shared code and fields;
- cannot be created with new
- both let callers depend on
- the what, not the how
- lesson six compares them
vs encapsulation
People often mix up abstraction and encapsulation. Abstraction is a design decision about what callers should see: a courier can quote and ship. Encapsulation is the mechanism that keeps the rest out of reach: the fee fields are private and cannot be changed from outside. You choose the abstraction first, then use encapsulation to protect it. They work together, but they answer different questions.
- abstraction:
- design-level choice of
- WHAT callers see
- (Courier: quote + ship)
- encapsulation:
- enforcing that the hidden
- part cannot be touched
- (private fee fields)
- they work together
Leaky abstractions
An abstraction leaks when callers still need the hidden details to use it correctly. Signs include method names that describe the how, like ship via hub Pune, callers catching database errors from something that was supposed to hide the database, or callers checking which concrete class they really have. When you see a leak, fix the contract instead of adding more special cases in the callers.
- • method names expose the
- how: shipViaHubPune()
- • callers catch SqlException
- from a "repository"
- • callers check
- "if (c instanceof Air)"
- • results mean different
- things per implementation
- fix: change the contract
When not to
Abstraction is not free. Every interface is one more file and one more jump when someone reads the code. Add one when there are several real implementations, when tests need a fake, or at a boundary with another system such as payments, email or a database. An interface with one implementation that will never change, added just in case, mostly adds noise.
- every interface is one more
- file and one more jump when
- reading code
- good reasons:
- several real implementations
- a fake needed for tests
- a boundary to another system
- weak reason: "just in case"
In interviews
In design rounds, abstraction is how you show the design can grow. Find what varies and put it behind an interface named after its job. A payment method, a pricing policy for a parking lot, a notifier, a sink for a logger. Then the core classes depend only on those interfaces. Common mistakes are names that describe the how, and creating an interface for every class whether it varies or not.
- payment: PaymentMethod
- parking: PricingPolicy
- notifications: Notifier
- vending machine: Dispenser
- logger: Sink, Formatter
- mistake: interfaces named
- after the how, or one
- interface per class