Writing
Programming Principles Worth Knowing: DRY, KISS, Single Responsibility and Open/Closed
DRY, KISS, single responsibility and open/closed still protect maintainability. Here’s what each one really means, why duplication can be cheaper than the wrong abstraction, and when to bend the rules.
By Ka Lun Chan · Engineering judgment / Learning
Which programming principles are worth knowing?
Four cover most of what matters day to day: don’t repeat yourself (DRY), keep it simple (KISS), single responsibility and open/closed. Each one protects maintainability, but each is easy to overapply, so learn what its author meant and when to bend it.
I first wrote this on my old blog. This version keeps the advice that held up, and corrects the part where I oversold DRY.
The starting point hasn’t changed. Don’t settle for code that works. Aim for code that’s readable, maintainable and fast enough. Software is a team sport, and the simplest way to make your code easy for other developers to follow is to keep it simple. Maintainability matters because software is never finished: it keeps needing new features and bug fixes, and someone has to make those changes safely. I wrote more about that habit in how to be a better developer.
| Principle | What it really means | When to bend it |
|---|---|---|
| DRY | Every piece of knowledge, such as a business rule, a schema or a config value, has one authoritative home | Two pieces of code look alike but represent different decisions that will change for different reasons |
| KISS | Choose the simplest design that meets the real requirements, so the next person can follow it | A requirement you can name, such as a recovery target or measured load, needs more machinery |
| Single responsibility | A module has one reason to change: it answers to one group of people | Splitting would scatter one small concern across files nobody needs to change separately |
| Open/closed | Add new behavior by adding code, without editing code that already works | You only have one or two cases, or the variation point is still a guess |
Is DRY the most important principle?
No, and I was wrong to call it that. DRY is about not duplicating knowledge, such as a business rule, and it’s still one of the most useful ideas in programming. Applied to code that merely looks similar, it produces abstractions that cost more than the duplication they removed.
My original argument still stands for real duplication. When the same rule lives in two places, the copies drift apart, every change has to be made twice, and the one you forget becomes a bug. DRY was never meant as a time saver. It’s about having one place to change.
What I missed is what DRY covers. Dave Thomas, co-author of The Pragmatic Programmer, described it in an interview with Artima as every piece of system knowledge having one authoritative, unambiguous representation, and pointed out that knowledge includes schemas, test plans, the build and documentation. Two functions with similar lines can represent two different decisions. Merging them couples those decisions.
The counterweight I’d now teach alongside DRY comes from Sandi Metz. In The Wrong Abstraction she argues that “duplication is far cheaper than the wrong abstraction.” Her pattern is familiar: someone extracts shared code, the next requirement almost fits, so they add a parameter and a conditional, and after a few rounds nobody understands the helper. Her fix is to inline it back into each caller, delete what each caller doesn’t need, and look for the right abstraction again.
# One shared helper that grew a flag for every new caller
def format_line(item, show_price=True, show_sku=False, for_warehouse=False):
parts = [item.sku.ljust(12) if show_sku else item.name.ljust(30)]
if for_warehouse:
parts.append(item.bin_location.ljust(8))
parts.append(str(item.qty).rjust(5))
if show_price and not for_warehouse:
parts.append(f"{item.price:>10.2f}")
return "".join(parts)
# Two small functions that look alike but can change independently
def invoice_line(item):
return f"{item.name:<30}{item.qty:>5}{item.price:>10.2f}"
def pick_list_line(item):
return f"{item.sku:<12}{item.bin_location:<8}{item.qty:>5}"The invoice and the pick list share a shape today. They answer to different people, so they’ll diverge. Two short functions are easier to read and safer to change than one function with three flags.
Two rules of thumb help here. The rule of three, attributed to Don Roberts and popularized by Martin Fowler’s Refactoring, says to tolerate the second copy and extract on the third, when you can see what actually varies. Kent C. Dodds calls the same instinct AHA programming: avoid hasty abstractions. That’s also why my original line that 100% DRY software is near impossible is true for a better reason than I gave. You shouldn’t aim for it. When you do extract, well-named functions are usually the right first step, and refactoring is where you get the chance.
What does keep it simple mean in practice?
Build the simplest thing that meets the requirements you actually have. Simple code takes less time to write, has fewer places for bugs to hide and is easier to change.
The phrase is usually credited to Kelly Johnson, the engineer who led Lockheed’s Skunk Works, whose point was that a jet had to be repairable in the field with a handful of tools. That’s a better framing than the slogan. Simplicity is measured by the person who has to fix it later. Steve Jobs put the hard part well in a BusinessWeek interview: “Simple can be harder than complex.” The first design that works is rarely the simplest one.
Simple doesn’t mean careless. A small design still needs error handling, tests and clear boundaries. It means each piece of complexity has a requirement you can name behind it. That applies far beyond a single function. I’ve written about the architecture you don’t build and about the hidden cost of scaling too early, where every extra service, queue and database keeps asking for attention after launch.
What does single responsibility actually mean?
A module should have one reason to change. Robert C. Martin, who named the principle, says that reason is a person or group: code that answers to one part of the business belongs together, and code that answers to different people should be separated.
I originally wrote that each class should do one thing and one thing only. That’s the common reading, and it pushes people toward lots of tiny classes. In his own post on the principle, Martin states it as “one and only one reason to change” and then adds, “This principle is about people.” If the finance team and the warehouse team can both ask you to change the same class, a change for one can break the other.
My old analogy still works with that correction. American schools teach American English in English class. They don’t teach American and British spelling together in one lesson, because the two follow different authorities and change on their own terms. Mixing them confuses students the same way mixing two stakeholders’ rules in one class confuses the next developer. The invoice and pick list functions above are the same idea at a smaller scale. For more on classes themselves, see thinking in objects.
How do you write code that’s open for extension and closed for modification?
Find the point where behavior varies and give it a stable shape, so a new case means adding code instead of editing code that already works. In everyday code that’s often a strategy object or a dictionary of handlers.
Bertrand Meyer named the principle in Object-Oriented Software Construction, using inheritance to extend a class without changing it. Martin later restated it as being able to extend a system’s behavior without modifying that system, the idea behind plugin architectures. You don’t need class hierarchies to get the benefit:
from decimal import Decimal
def standard(order):
return Decimal("5.00")
def express(order):
return Decimal("15.00") + Decimal("0.50") * order.weight_kg
SHIPPING_RATES = {
"standard": standard,
"express": express,
}
def shipping_cost(order):
try:
rate = SHIPPING_RATES[order.method]
except KeyError:
raise ValueError(f"Unknown shipping method: {order.method}") from None
return rate(order)
# A new method is a new function and one new entry. shipping_cost() doesn't change.
def pickup(order):
return Decimal("0.00")
SHIPPING_RATES["pickup"] = pickupAdding a shipping method no longer means touching an if/elif chain that every other method depends on. The core function stays tested and unchanged.
My original phrasing was that we should write code that doesn’t have to change every time a requirement changes. That needs a qualifier. You can only close code against the changes you predicted. Guess wrong and you’ve built an extension point nobody uses, which is the same trap as a hasty abstraction. With two shipping methods, a plain if is fine. When the third one arrives, the variation point is real and worth formalizing.
How should you apply these principles on a real team?
Use them as prompts in design and code review, and check each one against the code in front of you. The useful question is always the same: will this make the next change easier or harder for someone else?
- When you spot duplication, ask whether it’s the same knowledge or a coincidence. Only the first needs one home.
- When a helper grows a flag for a new caller, consider inlining it instead.
- When a class changes for reasons coming from two different teams, split it along that line.
- When you add an extension point, name the second and third cases that will use it.
The principles all point at the same goal I started with: code that other developers can read, trust and change. When following one of them makes the code harder to follow, bend it and leave a comment that explains why.
Sources
Checked in November against Sandi Metz’s own post, Dave Thomas’s Artima interview and the Pragmatic Bookshelf page for The Pragmatic Programmer, Robert C. Martin’s posts on single responsibility and open/closed, Kent C. Dodds on AHA, and reference pages on KISS, the rule of three and the open/closed principle. The table and code examples are mine.
- Sandi Metz: The Wrong Abstraction
- Artima: Orthogonality and the DRY Principle, a conversation with Dave Thomas
- Pragmatic Bookshelf: The Pragmatic Programmer, 20th Anniversary Edition
- Robert C. Martin: The Single Responsibility Principle
- Robert C. Martin: The Open Closed Principle
- Kent C. Dodds: AHA Programming
- Wikipedia: Rule of three (computer programming)
- Wikipedia: KISS principle
- Wikipedia: Open-closed principle
Short answers
Is DRY the most important programming principle?
It’s one of the most useful, but it isn’t a rule to apply everywhere. DRY is about giving each piece of knowledge, such as a business rule, one authoritative home. Merging code that only looks similar creates abstractions that cost more than the duplication, which is why Sandi Metz says duplication is far cheaper than the wrong abstraction.
When should I remove duplicated code?
When the copies represent the same knowledge and will change together. A common rule of thumb is the rule of three: tolerate the second copy and extract on the third, once you can see what actually varies.
What does the single responsibility principle mean?
Robert C. Martin defines it as a module having one reason to change, and says that reason is a person or group. Code that answers to one part of the business belongs together; code that answers to different people should be separated.
How do I apply the open/closed principle in Python or JavaScript?
Give the point where behavior varies a stable shape, such as a strategy object or a dictionary of handlers, so a new case means adding a function and an entry instead of editing working code. Only do it once the variation is real; with one or two cases, a plain if statement is fine.
Write for the next developer
Pick one shared helper in your codebase that has grown a flag or two, and ask whether each caller still needs it. Inlining one bad abstraction teaches more about these principles than memorizing all four.