Imagine you are building an e-commerce system.
You need to calculate tax.
Order Module:
double calculateTax(double amount)
{
return amount * 0.18;
}Invoice Module:
double calculateTax(double amount)
{
return amount * 0.18;
}Payment Module:
double calculateTax(double amount)
{
return amount * 0.18;
}Reporting Module:
double calculateTax(double amount)
{
return amount * 0.18;
}Everything works.
Until one day:
Tax Rate Changed
18% to 20%Now developers must find:
Every Tax Calculationin the entire codebase.
Some missed one location.
Result:
Orders = 20%
Invoices = 20%
Reports = 18%Business inconsistency.
Production bugs.
Customer complaints.
Financial discrepancies.
This exact problem led to one of the most influential principles in software engineering.
DRY тАУ Don't Repeat Yourself.
Historical Background
DRY was introduces in the book: The Pragmatic Programmer
by:
- Andrew Hunt
- David Thomas
Their original statement:
Every piece of knowledge must have a single, unambiguous, authoritative representation within a system.
Notice something important.
They did NOT say:
Don't Repeat Code
They said:
Don't Repeate Knowledge
This distinction is critical.
The Most Common Misunderstanding
Most developers think:
DRY = No Duplicate CodeWrong.
Actual DRY:
DRY = No Duplicate KnowledgeThese are not the same thing.
Understanding Knowledge Duplication
Suppose:
double calculateGST(double amount)
{
return amount * 0.18;
}And elsewhere:
double calculateInvoiceGST(double amount)
{
return amount * 0.18;
}This duplicates:
Tax Rule KnowledgeIf tax changes, both must change.
This violates DRY.
Understanding Code Duplication
Now consider:
void printHeader()
{
std::cout << "Welcome";
}And:
void printFooter()
{
std::cout << "Thank You";
}Some developers attempt:
void printMessage(...)to avoid duplication.
But:
Header and Footer
Represent Different KnowledgeEven if code looks similar.
DRY is NOT violated.
The Single Source of Truth
The core goal of DRY is:
One Fact
One LocationExample:
Bad:
const double GST_ORDER = 0.18;
const double GST_INVOICE = 0.18;
const double GST_PAYMENT = 0.18;Good:
class TaxConfiguration
{
public:
static constexpr double GST = 0.18;
};Now:
One Truthexists.
Changes happen once.
Consistency is preserved.
Why Duplication Is Dangerous
Every duplicated piece of knowledge creates:
Multiple Maintenance PointsExample:
Tax Ruleappears:
12 TimesNew regulation arrives.
Developer updates:
11 PlacesMisses:
1 PlaceBug appears.
This is called:
Shotgun SurgeryOne change requires modifying many locations.
A classic code smell.
Rule of Three
A common guideline:
Do NOT abstract after: 1 occurrence
Be cautious after: 2 occurrences
Strongly consider abstraction after: 3 corrences
Known as: Rule of Three
Leave a comment
Your email address will not be published. Required fields are marked *


