Designing Good Class Interfaces
Design small, cohesive classes: tell objects what to do, prefer immutable value objects, and tell identity apart from equality when comparing objects.
Welcome back!
Step 1 of 14Learn
Tell, don't ask
Compare two ways to apply a discount:
// Asking: outside code pulls data out, decides, and pushes it back
if (order.getStatus() === 'open' && order.getTotal() > 100) {
order.setTotal(order.getTotal() * 0.9);
}
// Telling: the order makes its own decision
order.applyBulkDiscount();The first version spreads the order's rules across the codebase. Every place that discounts orders must remember to check the status, and if the rule changes (say, discounts no longer apply to gift cards), you hunt down every copy.
The second follows a guideline called tell, don't ask: instead of asking an object for its data and acting on it, tell the object what you want and let it use its own data. The rule lives in one place, inside Order.
A related warning sign is a class made entirely of getters and setters with no real behavior, sometimes called an anemic model. It looks object-oriented but is really a data bag with extra steps; all the logic lives elsewhere and encapsulation offers no protection. A setter for every field is an especially strong smell, because it lets anyone change anything.
Getters aren't evil. Showing an order total on screen requires reading it. The test is where the decisions happen: if outside code reads several fields and then decides how the object should change, that logic probably belongs inside the object.
Step 2 of 14Practice · What would you do?
What would you do?
In a library app, checkout code looks like this:
if (book.getCopiesAvailable() > 0 && !member.isSuspended()) {
book.setCopiesAvailable(book.getCopiesAvailable() - 1);
member.getLoans().push(book);
}The same logic is copied into the web app, the kiosk app and an admin script. What is the best refactoring?
Step 3 of 14Compare
Asking vs telling
| Aspect | Ask (pull data, decide outside) | Tell (object decides) |
|---|---|---|
| Example | if (order.getStatus() === "open" && ...) order.setTotal(...) | order.applyBulkDiscount() |
| Where the rule lives | Copied into every caller | Once, inside Order |
| When the rule changes | Hunt down every copy | Edit one method |
| Typical smell | A setter for every field | Methods named after behavior |
Step 4 of 14Learn
Cohesion: one class, one clear job
A class is cohesive when its fields and methods all serve one clear purpose. A quick test: try to describe the class in one sentence without using "and". "Represents a customer's shopping cart" passes. "Handles the cart and sends emails and writes the sales report" doesn't.
Low cohesion causes real pain:
- Changes collide. If one class formats invoices and also talks to the database, a database change risks breaking invoice formatting.
- Testing gets hard. To test the formatting, you now need a database.
- Reuse is impossible. You can't reuse the formatting in another app without dragging the database code along.
Signs that a class is doing too much: it has many fields that only some methods use; its name is vague (Manager, Helper, Utils, Processor); it's hundreds of lines long; or a method's name contains "and".
The opposite mistake exists too. Splitting a simple concept into a dozen tiny classes that each hold one line of code makes a design harder to follow. Aim for classes that are about one thing, sized so that a reader can hold the whole class in their head.
Closely related is coupling: how much one class depends on the internals of another. Good designs have high cohesion and low coupling, so each class does one job well and can change without forcing changes elsewhere.
Step 5 of 14Practice · Sort into groups
Sort each design trait into "helps" (high cohesion, low coupling) or "hurts".
Tap an item, then tap its group (or drag it there).
Step 6 of 14Practice · Diagram
Cohesion and coupling
Tap the quadrant good designs aim for.
Tap the shape that answers the question, then press Check.
- Focused and independent
One job, few dependencies: the target.
- Focused but tangled
Each class does one thing but reaches into others' internals.
- Grab-bag utilities
Unrelated helpers lumped together, like a Utils class.
- Big ball of mud
Classes do many things and depend on everything.
Step 7 of 14Learn
Value objects and immutability
Some objects have identity: two customers named Alex Kim are still different customers. Others are defined entirely by their values. A value object such as Money(25, 'USD'), a date, a color or a coordinate has no identity of its own: any two Money(25, 'USD') are interchangeable.
Value objects work best when they are immutable: once created, they never change. Operations return a new object instead:
class Money {
#cents; #currency;
constructor(cents, currency) {
if (!Number.isInteger(cents)) throw new Error('Use whole cents');
this.#cents = cents; this.#currency = currency;
Object.freeze(this);
}
add(other) {
if (other.currency !== this.#currency) throw new Error('Currency mismatch');
return new Money(this.#cents + other.cents, this.#currency); // new object
}
get cents() { return this.#cents; }
get currency() { return this.#currency; }
equals(other) { return other.cents === this.#cents && other.currency === this.#currency; }
}Why immutability helps:
- Safe sharing. If a price object is shared by ten orders, none of them can change it under the others.
- No aliasing surprises. The reference bugs from earlier vanish when nothing can be modified.
- Validated once. The constructor checks the values; after that they can never become invalid.
Notice the cents. Storing money as integer cents avoids floating-point surprises such as 0.1 + 0.2 producing 0.30000000000000004.
Step 8 of 14Practice · Work it out
A Money object stores whole cents. A cart contains three items priced $19.99, $5.25 and $0.76. What is the total in cents that the cart should store?
Step 9 of 14Compare
Entity vs. value object
| Aspect | Entity | Value object |
|---|---|---|
| Defined by | Identity (an ID that stays the same) | Its values only |
| Examples | Customer, Order, BankAccount, Player | Money, DateRange, Color, Coordinate, EmailAddress |
| Changes over time | Yes: an order moves from open to shipped | No: create a new one instead |
| Equal when | IDs match | All fields match |
Step 10 of 14Practice · Choose one
Which object is the best candidate to be an immutable value object?
Step 11 of 14Practice · Fill in the blanks
Fill in the blanks
In JavaScript, a === b on two objects tests : whether both names point to the same object. To compare value objects by their contents, a class usually provides an method.
Step 12 of 14Learn
Equality, hashing and collections
Identity versus equality matters most when objects go into collections. Suppose you keep a Set of coordinates already visited in a game:
const visited = new Set();
visited.add(new Point(2, 3));
visited.has(new Point(2, 3)); // falseThe answer is false because JavaScript's Set and Map compare object keys by identity, and the second Point is a different object. Common fixes are to store a value-based key, such as the string "2,3", or to keep the original objects and look them up with an equals check.
Other languages build this in. In Python, a class that defines __eq__ and __hash__ works correctly as a dictionary key or set member. In Java and C#, you override equals and hashCode (or GetHashCode) together; overriding only one is a classic bug that makes lookups fail in confusing ways. Java records, C# records and Python dataclasses can generate value-based equality for you.
The rule underneath: entities compare by identity, value objects compare by contents, and your collections must use the same notion of "same" that your model does.
Step 13 of 14Practice · Choose one
A program stores visited squares as Point objects in a JavaScript Set. Why does visited.has(new Point(1, 1)) return false even after a point (1, 1) was added?
Step 14 of 14Practice · True or false
Making a value object immutable means that once it is created, any change is expressed by creating and returning a new object.
Lesson complete!