The cost of unnecessary abstraction
What you will learn on this page
Section titled “What you will learn on this page”- What an unnecessary abstraction costs: in reading time, in debugging, and in the effort of every later change.
- How to recognise the common forms: speculative generality, indirection without variation, and an interface for every class.
- Four questions that tell an abstraction that pays for itself from one that does not.
- How to remove an abstraction safely, and when building one up front is the right call.
The problem
Section titled “The problem”A web service is adding sign-up. One small part of it:
- FR-1 After sign-up, the new user is sent a welcome message that
names them and says how long their free trial lasts:
Welcome, Kim! Your free trial lasts 14 days. - FR-2 A one-day trial says
1 day, not1 days. - FR-3 A user who gave no name gets
Welcome!with no name. - FR-4 A trial shorter than one day is a programming error and must
be refused. The trial length comes from sign-up code that another team
owns, so the function throws an exception rather than trusting an
assertthat release builds remove.
A developer who has just learned about interfaces and factories wants to “do it properly” and writes the version below. It compiles, it is tested, and it produces exactly the right text. Nothing about it is wrong. The question this page asks is what it costs.
What abstraction costs, and what it buys
Section titled “What abstraction costs, and what it buys”Every abstraction is a trade. It buys a place where things can vary without the callers changing. It costs something every time anyone reads, debugs, or changes the code, whether or not anything ever varies.
| Cost | What it looks like |
|---|---|
| Reading | To find what the code does, you follow calls through interfaces, factories, and wrappers before you reach the line that does the work |
| Debugging | “Go to definition” on a virtual call lands on the interface, not the code; stack traces are deeper; you must find which implementation is live |
| Changing | A change to what the code does touches the interface, the implementation, the factory, and the tests of each |
| Naming and concepts | Every type is a name a reader must learn; invented names (NameProvider) say less than plain code (user.name) |
| Testing | More objects to build in each test; tests of plumbing (does the factory return the right type?) instead of behaviour |
When the variation is real, the trade is good: the cost is paid once, and every new variant is cheap. When the variation never arrives, you pay the cost forever and get nothing for it. That is speculative generality: abstraction built for a future that has not been asked for.
The over-built version
Section titled “The over-built version”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Follow the call that builds one greeting: GreetingService::greet asks a// NameProvider for the name, then a GreetingFormatter for the text. Each// of those is an interface with exactly one class behind it, made by a// factory that can make one kind. Everything is correct; none of it varies.
// The input: a user's name (may be empty) and the trial length in days.struct User { std::string name; int trial_days;};
// "In case the name comes from somewhere else one day."// An interface: `= 0` means each derived class must supply name_of.// The only one, UserNameProvider, just returns user.name.class NameProvider {public: virtual ~NameProvider() = default; virtual std::string name_of(const User& user) const = 0;
protected: // The usual interface boilerplate: protected so that only derived // classes can create or copy the base part, which prevents slicing. NameProvider() = default; NameProvider(const NameProvider&) = default; NameProvider& operator=(const NameProvider&) = default;};
class UserNameProvider final : public NameProvider {public: std::string name_of(const User& user) const override;};
// Options nobody has asked for; every one has its default.// The program never sets any of them, so salutation is always "Welcome",// punctuation always "!", and shout always false.struct GreetingConfig { std::string salutation = "Welcome"; std::string punctuation = "!"; bool shout = false;};
// "In case we need other formats."// A second interface, again with one implementation. Its format() is the// only function in this file that does real work.class GreetingFormatter {public: virtual ~GreetingFormatter() = default; virtual std::string format(const std::string& name, int trial_days) const = 0;
protected: GreetingFormatter() = default; GreetingFormatter(const GreetingFormatter&) = default; GreetingFormatter& operator=(const GreetingFormatter&) = default;};
// Builds the message from a name and a trial length, using its own copy// of the config. Throws std::invalid_argument if trial_days is below 1.class DefaultGreetingFormatter final : public GreetingFormatter {public: explicit DefaultGreetingFormatter(GreetingConfig config); std::string format(const std::string& name, int trial_days) const override;
private: GreetingConfig config_;};
enum class FormatterKind { standard }; // one kind
// A factory: a function whose job is to choose and create an object. It// returns a std::unique_ptr, so the caller owns the new formatter. With// one kind, the choice it makes is always the same.class GreetingFormatterFactory final {public: static std::unique_ptr<GreetingFormatter> create(FormatterKind kind, GreetingConfig config);};
// Owns one of each part, through std::unique_ptr, and forwards to them.class GreetingService final {public: // Takes ownership of both parts. Throws std::invalid_argument if // either pointer is null. GreetingService(std::unique_ptr<NameProvider> names, std::unique_ptr<GreetingFormatter> formatter); // Calls names_->name_of(user), then formatter_->format(...) with that // name and user.trial_days, and returns the result. std::string greet(const User& user) const;
private: std::unique_ptr<NameProvider> names_; std::unique_ptr<GreetingFormatter> formatter_;};
// The only way the program ever builds a service.// It plugs in a UserNameProvider and the factory's standard formatter// with a default GreetingConfig{}.GreetingService make_default_greeting_service();VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The behaviour. A reader starting at main looks through four other// functions before reaching it.// Builds, for example, "Welcome, Kim! Your free trial lasts 14 days."// piece by piece: += adds text to the end of `text`. Throws// std::invalid_argument if trial_days is below 1.std::string DefaultGreetingFormatter::format(const std::string& name, int trial_days) const { if (trial_days < 1) { throw std::invalid_argument{"a trial lasts at least 1 day"}; } std::string text = config_.salutation; // always "Welcome" in this program if (!name.empty()) { text += ", " + name; // an empty name gives "Welcome!" with no comma } // std::to_string turns the number into digits; `?:` picks the singular // "day." for exactly 1 and the plural "days." otherwise. text += config_.punctuation + " Your free trial lasts " + std::to_string(trial_days) + (trial_days == 1 ? " day." : " days."); // Never runs here: nothing sets shout to true. It would turn every // letter into a capital. `char& letter` changes each character in // place. std::toupper needs an unsigned char value (a negative char // would be undefined behaviour), and its int result is cast back to char. if (config_.shout) { for (char& letter : text) { letter = static_cast<char>(std::toupper(static_cast<unsigned char>(letter))); } } return text;}How this code works: One greeting through the over-built version
The other functions live in overbuilt.cpp but are not shown above. This
is what happens, in order, when main greets Kim with a 14-day trial.
Building the service (once). make_default_greeting_service():
- creates a
UserNameProviderwithstd::make_unique, which returns astd::unique_ptrthat owns it; - calls
GreetingFormatterFactory::create(FormatterKind::standard, GreetingConfig{}). The factory’sswitchhas onecase, so it always creates aDefaultGreetingFormatterholding the default options ("Welcome","!", no shouting); - passes both pointers to the
GreetingServiceconstructor, which moves them into its members and throwsstd::invalid_argumentif either is null. The service now owns both parts, and they are destroyed with it.
Greeting one user. service.greet({"Kim", 14}):
greetcallsnames_->name_of(user), a virtual call that reachesUserNameProvider::name_of, which returns"Kim".greetthen callsformatter_->format("Kim", 14), a second virtual call that reachesDefaultGreetingFormatter::format, the code shown above.formatchecks the trial, then builds the text:
| Step | text afterwards |
|---|---|
| start with the salutation | Welcome |
| the name is not empty | Welcome, Kim |
| punctuation and the trial | Welcome, Kim! Your free trial lasts 14 days. |
shout is false |
unchanged |
Five functions and two virtual calls to produce one sentence. The right-sized version below does the same work in one function.
struct User
Data members
std::string name;int trial_days;
interface (abstract class) NameProvider
one implementation, no test double
Member functions
virtual std::string name_of(const User& user) const = 0;
class UserNameProvider final
implements NameProvider; returns user.name
Member functions
std::string name_of(const User& user) const override;
struct GreetingConfig
nobody sets these
Data members
std::string salutation;"Welcome"std::string punctuation;"!"bool shout;false
interface (abstract class) GreetingFormatter
one implementation, no test double
Member functions
virtual std::string format(const std::string& name, int trial_days) const = 0;
class DefaultGreetingFormatter final
implements GreetingFormatter; the only real behaviour
Data members
GreetingConfig config_;
Member functions
std::string format(const std::string& name, int trial_days) const override;
enum class FormatterKind
one value
Values
standard
class GreetingFormatterFactory final
creates the one kind
Member functions
static std::unique_ptr<GreetingFormatter> create(FormatterKind kind, GreetingConfig config);
class GreetingService final
forwards to the two interfaces
Data members
std::unique_ptr<NameProvider> names_;std::unique_ptr<GreetingFormatter> formatter_;
Member functions
std::string greet(const User& user) const;
The outline leaves out the constructors, the free function
make_default_greeting_service(), and the interfaces’ virtual
destructors and protected copy operations.
Step 1: question each abstraction
Section titled “Step 1: question each abstraction”For each type that exists to abstract (not to hold data), ask four questions:
- Variation: how many implementations exist today, counting test doubles?
- Boundary: does it hide something external or volatile: a file, a network, a device, the clock, a third-party library?
- Concept: does it name something from the requirements or the domain?
- Inlining: if you replaced it with the code it hides, would the caller become harder to read?
The four answers do not all justify the same thing. An interface or an extra layer (a factory, a service, a provider) needs a “yes” to Variation (two or more implementations today, and a test fake counts) or to Boundary. A “yes” to Concept or to Inlining justifies a type or a function that names an idea, not a layer of indirection in front of it. Here is the over-built version, type by type:
| Type | Variation | Boundary | Concept | Inlining hurts? | Verdict |
|---|---|---|---|---|---|
NameProvider, UserNameProvider |
1, no fake | no | no (“provider” of a field) | no: it is user.name |
remove |
GreetingFormatter |
1, no fake | no | no | no | remove |
DefaultGreetingFormatter |
(the one) | no | yes: “the welcome message” | it is the behaviour | keep the code, as a function |
GreetingConfig |
never set | no | no requirement mentions it | no | remove |
FormatterKind, the factory |
1 kind | no | no | no: make_unique would do |
remove |
GreetingService |
1 | no | no | no: it only forwards | remove |
User |
(data) | n/a | yes: the new user | n/a | keep |
Notice what the questions do not ask: “might we need this one day?” Almost anything might be needed one day. The questions ask about today, and about what the code hides.
Bad, good, great: the welcome message
Section titled “Bad, good, great: the welcome message”Text description of the diagram
Two parts, before and after. Before: main has two flow arrows. One goes to make_default_greeting_service, which leads to GreetingFormatterFactory::create with FormatterKind::standard. The other goes to GreetingService::greet. GreetingService::greet has two dashed arrows labelled “virtual”: one to NameProvider::name_of, implemented by UserNameProvider, which returns user.name; and one to GreetingFormatter::format, implemented by DefaultGreetingFormatter, which leads to the message text. After: main has a flow arrow to welcome_message(user), which leads to the message text. A flow arrow from the Before group to the After group shows the redesign.
Diagram source (Mermaid)
flowchart TB
subgraph Before
BM["main"] --> BF["make_default_greeting_service()"]
BF --> BK["GreetingFormatterFactory::create<br/>FormatterKind::standard"]
BM --> BS["GreetingService::greet"]
BS -.->|virtual| BN["NameProvider::name_of<br/>UserNameProvider: user.name"]
BS -.->|virtual| BG["GreetingFormatter::format<br/>DefaultGreetingFormatter"]
BG --> BT["the message text"]
end
subgraph After
AM["main"] --> AW["welcome_message(user)"]
AW --> AT["the message text"]
end
Before --> AfterThe right-sized version
Section titled “The right-sized version”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The right-sized version: plain data and one free function. Everything// a reader needs to check the message against the requirements is in// welcome_message.struct NewUser { std::string name; // may be empty int trial_days; // at least 1};
// For example "Welcome, Kim! Your free trial lasts 14 days."// Throws std::invalid_argument if trial_days is below 1.std::string welcome_message(const NewUser& user);VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Refuse a bad trial first, then build the two parts that vary, then join// everything in one return statement.std::string welcome_message(const NewUser& user) { if (user.trial_days < 1) { throw std::invalid_argument{"a trial lasts at least 1 day"}; } // `?:` picks one of two values. No name: nothing. A name: ", Kim". // The two sides have different types ("" is a plain C string, the // other a std::string), and the result becomes a std::string. const std::string who = user.name.empty() ? "" : ", " + user.name; const std::string days = user.trial_days == 1 ? " day." : " days."; // 1 day, 2 days // "Welcome" + who works because `who` is a std::string: adding a C // string to a std::string makes a new std::string, and so on left to right. return "Welcome" + who + "! Your free trial lasts " + std::to_string(user.trial_days) + days;}Every requirement is visible in the function: FR-4 is the check, FR-3 is
who, FR-2 is days, FR-1 is the return statement. A reader can check
the code against the requirements in a few seconds.
struct NewUser
Data members
std::string name;may be emptyint trial_days;at least 1
interface (abstract class) MessageSender
hides email, SMS, or a queue; faked in the tests
Member functions
virtual void send(std::string_view address, std::string_view text) = 0;
The two free functions are welcome_message(const NewUser&), which
throws std::invalid_argument for a trial below one day, and
send_welcome(user, address, sender), which also refuses an empty
address.
The abstraction that earns its place
Section titled “The abstraction that earns its place”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The one interface this program needs. It hides something external// (email, SMS, a message queue) and the tests need a fake for it.// A real program would have an email or SMS class behind it; this example// has a TerminalSender in main.cpp and a RecordingSender in the tests.class MessageSender {public: virtual ~MessageSender() = default; // Delivers `text` to `address`. std::string_view lets a caller pass a // std::string or a "string literal" without copying it; the view is // valid only during the call, so a sender that keeps the text must copy it. // Not const: sending is an action, and a sender may record or count it. virtual void send(std::string_view address, std::string_view text) = 0;
protected: MessageSender() = default; MessageSender(const MessageSender&) = default; MessageSender& operator=(const MessageSender&) = default;};
// Throws std::invalid_argument for an empty address or a bad trial.// Builds the message with welcome_message and hands it to `sender`, which// is borrowed for the call (a reference, not owned). If either check// fails, it throws before anything is sent.void send_welcome(const NewUser& user, std::string_view address, MessageSender& sender);Run the four questions on MessageSender. Variation: two today, the
terminal sender in main and the recording fake in the tests.
Boundary: yes, it hides the channel that leaves the program.
Concept: “send a message” is in the requirement. It passes on three
counts. The difference from NameProvider is not the number of lines;
it is that this interface hides something that really varies and really
needs replacing in a test.
Measured, not guessed
Section titled “Measured, not guessed”Counted from the example files, leaving out blank lines and lines that hold only a comment (the files also carry explanatory comments for this site, which would distort the comparison):
| Version | Files | Lines | Types | Functions to read to understand the message |
|---|---|---|---|---|
| Over-built | overbuilt.hpp, overbuilt.cpp |
109 | 9 | 5 |
| Right-sized | greeting.hpp, greeting.cpp |
17 | 1 (NewUser) |
1 |
The five functions are the ones listed in the bad solution above:
make_default_greeting_service, GreetingFormatterFactory::create,
GreetingService::greet, UserNameProvider::name_of, and
DefaultGreetingFormatter::format. Constructors are not counted, so the
real number for the over-built version is higher: GreetingService has
a constructor that checks its two pointers. sender.hpp and
sender.cpp (the message channel) are left out of both rows, because
both designs would need them and only the right-sized program includes
them. The line count is the least
important column. The last one is what every reader pays, every time.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// `users` (made above this snippet) holds Kim with 14 days, Lee with 1,// and a user with no name and 30 days: the plural, the singular, and// the missing name. The right-sized version is one call per user.std::cout << "right-sized:\n";for (const NewUser& user : users) { std::cout << " " << welcome_message(user) << '\n';}
// The over-built version needs a service built first. greet takes an// overbuilt::User, a different type, so {user.name, user.trial_days}// builds one from the same two fields (copying the name).std::cout << "overbuilt:\n";const overbuilt::GreetingService service = overbuilt::make_default_greeting_service();for (const NewUser& user : users) { std::cout << " " << service.greet({user.name, user.trial_days}) << '\n';}right-sized: Welcome, Kim! Your free trial lasts 14 days. Welcome, Lee! Your free trial lasts 1 day. Welcome! Your free trial lasts 30 days.overbuilt: Welcome, Kim! Your free trial lasts 14 days. Welcome, Lee! Your free trial lasts 1 day. Welcome! Your free trial lasts 30 days.sent: to kim@example.com: Welcome, Kim! Your free trial lasts 14 days.The sent: lines come from the end of main, after the region shown.
It passes the first user to send_welcome with a TerminalSender, a
MessageSender that prints to the terminal in place of an email client.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// LLD_TEST(name) defines one test. LLD_CHECK(condition) records a failure// if the condition is false, LLD_CHECK_EQ(actual, expected) does the same// for an equality and prints both values when they differ, and// LLD_CHECK_THROWS(expression, type) fails unless the expression throws// that type of exception. They come from the site's small test header,// lld_test.hpp.
// The three cases from the requirements: plural, singular, and no name.// {"Kim", 14} builds a NewUser in place for the call.LLD_TEST(the_message_names_the_user_and_the_trial) { LLD_CHECK(welcome_message({"Kim", 14}) == "Welcome, Kim! Your free trial lasts 14 days."); LLD_CHECK(welcome_message({"Lee", 1}) == "Welcome, Lee! Your free trial lasts 1 day."); LLD_CHECK(welcome_message({"", 30}) == "Welcome! Your free trial lasts 30 days.");}
LLD_TEST(a_trial_shorter_than_a_day_is_refused) { LLD_CHECK_THROWS(welcome_message({"Kim", 0}), std::invalid_argument);}
// The over-built version is not wrong: for every user, including a name// with a space, it gives exactly the same text, and it refuses a 0-day// trial in the same way.LLD_TEST(both_versions_say_the_same_thing) { const overbuilt::GreetingService service = overbuilt::make_default_greeting_service(); const std::vector<NewUser> users{{"Kim", 14}, {"Lee", 1}, {"", 30}, {"Ana Maria", 7}}; for (const NewUser& user : users) { LLD_CHECK(service.greet({user.name, user.trial_days}) == welcome_message(user)); } LLD_CHECK_THROWS(service.greet({"Kim", 0}), std::invalid_argument);}
// RecordingSender (defined above this snippet) is a fake MessageSender: it// keeps each "address: text" in a vector instead of sending it. The test// checks the one message it recorded, then that an empty address throws// and that the failed call added nothing, so the size is still 1.// std::size_t{1} makes the expected value the same type as size().LLD_TEST(the_welcome_goes_to_the_sender) { RecordingSender sender; send_welcome({"Kim", 14}, "kim@example.com", sender); LLD_CHECK(sender.sent == std::vector<std::string>{ "kim@example.com: Welcome, Kim! Your free trial lasts 14 days."}); LLD_CHECK_THROWS(send_welcome({"Kim", 14}, "", sender), std::invalid_argument); LLD_CHECK_EQ(sender.sent.size(), std::size_t{1});}both_versions_say_the_same_thing is the honest comparison: the
over-built version is not buggy. Everything it adds is cost without
behaviour.
Limits of the example
Section titled “Limits of the example”- The feature is deliberately small, so the over-built version looks absurd. In real code the same pattern hides inside larger features, where it is harder to see: one interface per class “for testing” that no test ever fakes, or a factory that only ever makes one thing.
- The right-sized function builds strings with
+. That is fine for one message; code that builds many large strings would reserve space or use a stream.
When a requirement changes
Section titled “When a requirement changes”The real test of a design is the next change. Here are three.
Spanish-speaking users get the message in Spanish. The over-built
version “was ready” for other formats: add a SpanishGreetingFormatter
and FormatterKind::spanish. But the factory picks one formatter
when the service is built, and the language is chosen per user. The
speculative abstraction guessed the wrong axis of variation, and now it
is in the way: you need either a service per language or a new parameter
through every layer. The right-sized version grows the data and the
function:
enum class Language { english, spanish };
struct NewUser { std::string name; // may be empty int trial_days; // at least 1 // A default member value: code that does not mention the language, such // as NewUser{"Kim", 14}, still compiles and gets English. Language language = Language::english;};
// The language is chosen per user, by the data, so one function covers// both. The parts that do not depend on the language are worked out once.
std::string welcome_message(const NewUser& user) { if (user.trial_days < 1) { throw std::invalid_argument{"a trial lasts at least 1 day"}; } const std::string count = std::to_string(user.trial_days); const bool one = user.trial_days == 1; switch (user.language) { case Language::english: return "Welcome" + (user.name.empty() ? "" : ", " + user.name) + "! Your free trial lasts " + count + (one ? " day." : " days."); case Language::spanish: return "¡Te damos la bienvenida" + (user.name.empty() ? "" : ", " + user.name) + "! Tu prueba gratuita dura " + count + (one ? " día." : " días."); } throw std::invalid_argument{"unknown language"};}(A sketch, compiled and run separately with GCC and Clang; not part of
the example. The source file must be saved as UTF-8; MSVC also needs
/utf-8.) The default for language keeps existing code such as
NewUser{"Kim", 14} working. With
two languages, a switch is the simplest correct design. With twenty
languages maintained by translators, the right design is different
again: message templates loaded as data, not one class per language.
Neither is what the over-built version prepared for.
Messages can also go by SMS. This is the variation MessageSender
was built for: add an SmsSender that implements it. Nothing else
changes.
The marketing team wants to shout at users. Now, and only now,
shout has a requirement. Add it then, to the code that exists then.
When building the abstraction up front is right
Section titled “When building the abstraction up front is right”Sometimes the second implementation is not speculative:
- The requirements already name it. “Payments by card now, by bank transfer next quarter” is a requirement, not a guess.
- It is a boundary. Files, networks, devices, time, and randomness almost always need a seam for tests; see dependency direction and dependency inversion.
- Other teams or programs plug into it. A plugin interface or a library’s public API is hard to change later, so it is designed first. Changing a C++ library’s public types can break every program built against it; see PImpl, ABI, versioning, and compatibility.
- It is a cheap type, not a layer. A value type such as
MoneyorOrderIdis an abstraction that costs almost nothing to read, and it catches mistakes at compile time. The costs on this page come from indirection (calls through layers), not from types that name things.
How to remove an unnecessary abstraction
Section titled “How to remove an unnecessary abstraction”Removing one is a refactoring: small steps, tests green after each.
- Check the facts. Search for every implementation of the interface and every caller of the factory. Check that no caller sets the options you are about to delete.
- Write or keep a test of the behaviour (here,
both_versions_say_the_same_thing) before changing anything. - Inline the single implementation. Replace calls through the interface with calls to the concrete class, then delete the interface.
- Replace the factory with a direct constructor call or
std::make_unique, then delete the factory and the one-value enum. - Collapse forwarding layers. A class whose functions only call another object’s functions can usually be deleted; its callers call the real code.
- Turn a data-less class with one function into a free function.
The page on refactoring toward principles shows this way of working, in steps, on a larger example.
C++ notes
Section titled “C++ notes”- A virtual call usually prevents inlining unless the compiler can
work out the real type (for example, because the class is
finalor with link-time optimisation), and it hides the callee from “go to definition”. The human cost is usually much larger than the machine cost; measure before using performance as an argument either way. std::unique_ptrchains add allocations and null states.GreetingServicehas to check its two pointers for null in its constructor; a function has nothing to check.- Templates are abstraction too. A function template with five policy parameters, used with one set of arguments, has the same reading and changing costs as an interface with one implementation, without the virtual calls or the allocations, but with longer compile times and harder error messages.
- Free functions are fine in C++. Not everything has to be a class. A function in a namespace, taking a struct, is often the clearest design.
Trade-offs
Section titled “Trade-offs”| Keeping it simple gains | It risks |
|---|---|
| Code a reader can check against the requirements quickly | When a real variation arrives, someone has to add the abstraction then (usually a small, safe change) |
| Changes touch one place | Teams that equate “more classes” with “more professional” may push back |
| Tests test behaviour, not plumbing | A boundary left without a seam is hard to test; do not apply this page to I/O |
| The abstraction you add later fits the variation that really came | None of the above is a reason to skip validation, tests, or clear names |
Common mistakes
Section titled “Common mistakes”- One interface per class “for testing” when no test ever uses a fake. If the class has no external dependency, test it directly.
- A factory with one product, or an enum with one value “for later”.
- Configuration for options nobody asked for. Each option is a code path to test and document.
- Manager, Helper, Provider, Handler layers that only forward calls.
- Using a pattern because it is a pattern. A pattern is a solution to a problem; with no problem, it is only cost. The patterns section shows each pattern with the problem that justifies it.
- Swinging too far the other way: removing the seam in front of a database or a clock because “abstraction is bad”. The four questions keep those.
Exercise
Section titled “Exercise”Exercise: Simplify an over-engineered design
A weather app shows the current temperature in °C or °F, as the user prefers. The temperature comes from a sensor driver. Someone designed this:
interface (abstract class) Converter
Member functions
virtual double convert(double value) const = 0;
class CelsiusToFahrenheit final
implements Converter
Member functions
double convert(double value) const override;
class CelsiusToCelsius final
implements Converter
Member functions
double convert(double value) const override;returns value unchanged
class ConverterFactory final
Member functions
static std::unique_ptr<Converter> create(std::string_view unit_name);"C" or "F"
class ConverterRegistry final
a global singleton holding the factory
Member functions
static ConverterRegistry& instance();const ConverterFactory& factory() const;
interface (abstract class) TemperatureSource
implemented by the sensor driver and a test fake
Member functions
virtual double read_celsius() const = 0;
class DisplayService final
Data members
const TemperatureSource& source_;std::string unit_name_;
Member functions
std::string text() const;e.g. "21.5 °C"
- Run the four questions on each abstraction. Which earn their place?
- Sketch the simpler design.
- One requirement you might hear next is “also show Kelvin”. How much of your design changes?
Show the explained answer
1. TemperatureSource passes: it hides a device (a boundary) and has
two implementations today, the driver and the fake. Everything else
fails as a layer. DisplayService has data and one function, but its
only job is to produce a string, so it becomes a plain function that
takes the source and the unit. Converter has two implementations, but one does nothing, and
both exist only because of the interface. The factory makes one of two
things from a string, so a typo is found only at run time. The registry
is a global that exists only to hold the factory. The unit is a string,
which the compiler cannot check.
2.
enum class Unit
Values
celsiusfahrenheit
namespace weather
the app's own namespace
Functions
double from_celsius(double celsius, Unit unit);a switchstd::string temperature_text(double celsius, Unit unit);e.g. "21.5 °C"
interface (abstract class) TemperatureSource
kept: hides the sensor
Member functions
virtual double read_celsius() const = 0;
The display code reads the source and calls temperature_text. The
user’s preference is stored as a Unit, not a string, and the place
that reads the preference (a settings file, say) converts it once and
refuses unknown values there.
3. Add kelvin to Unit, one case to from_celsius, one to the
unit symbol in temperature_text, and one to the code that reads the
stored preference into a Unit. With -Wall (and no default: label),
GCC and Clang warn at every switch over Unit that misses kelvin,
which finds the first three places for you.
That is a smaller change than adding a class, a factory branch, and a
registry entry.
Summary
Section titled “Summary”- Abstraction buys a place for variation and costs reading, debugging, and change effort, whether or not the variation ever comes.
- Speculative generality is abstraction for a future nobody asked for: interfaces with one implementation and no fake, factories with one product, options nobody sets, layers that forward.
- Ask four questions: variation today, a boundary, a real concept, and whether inlining would hurt. An interface or layer needs variation or a boundary; a concept or readability justifies only a type or a function.
- Keep the seams in front of I/O, devices, time, and third-party code; keep cheap value types that name things.
- When a real variation arrives, add the abstraction then. It will fit the variation that really came, which a guess often does not.