Design Principles
The rules of thumb that keep classes small, focused and easy to change.
Principles such as single responsibility, open/closed, Liskov substitution, interface segregation and dependency inversion are not patterns you add; they are properties you check. Code that breaks them still runs, but every change costs more than it should.
Problems in this category ask you to find the principle being broken, usually through a concrete symptom: a class that changes for four unrelated reasons, a subclass that throws on half its methods, or business logic that can't be tested without a real database.
You'll recognise it when
- One class changes whenever pricing, layout or storage changes.
- A subclass overrides methods only to throw an exception.
- Business rules create their own database or HTTP clients.
- Callers read an object's data, decide, and write it back.
Example
A weather station sends alerts when rain is likely.
class RainAlert {
void check(Forecast f) {
if (f.rainChance() > 70) {
TwilioClient sms = new TwilioClient("AC9f…", "secret");
sms.send("+919800000000", "Carry an umbrella");
}
}
}interface AlertChannel {
void send(String message);
}
class RainAlert {
private final AlertChannel channel;
RainAlert(AlertChannel channel) { this.channel = channel; }
void check(Forecast f) {
if (f.rainChance() > 70) channel.send("Carry an umbrella");
}
}Why it's better: The rule (when to alert) no longer depends on how alerts are delivered. It can be tested with a fake channel, and SMS, email or push are plug-ins rather than edits.
Ideas you'll practise
Problems 17
- PR-01The Penguin That Can't FlyL1EasyFREE
- PR-02One Class Handles Every User TaskL1EasyComing soon
- PR-03The Invoice That Prints, Saves and Emails ItselfL1EasyComing soon
- PR-04Every New Payment Option Edits the Same ClassL1MediumComing soon
- PR-05Square Extends RectangleL1MediumComing soon
- PR-06A Read-Only Price List That Throws on AddL1MediumComing soon
- PR-07Robots Forced to EatL1EasyComing soon
- PR-08The Printer Interface With FaxL1EasyComing soon
- PR-09Order Logic Welded to the DatabaseL1EasyComing soon
- PR-10Business Logic Depends on the HTTP ClientL1MediumComing soon
- PR-11A Stack That Lets You Insert in the MiddleL1MediumComing soon
- PR-13Reaching Through Three Objects for a Postal CodeL1EasyComing soon
- PR-14Ask, Decide, SetL1EasyComing soon
- PR-15Public Balance FieldL1EasyComing soon
- PR-17Same Validation in Six PlacesL1EasyComing soon
- PR-19Configurable for Requirements That Never CameL3MediumComing soon
- PR-21The Utility Class Grab BagL1MediumComing soon