DRY — Explained with Examples
DRY (Don’t Repeat Yourself) is a software principle that states every piece of knowledge must have a single, unambiguous, authoritative representation.
DRY stands for Don’t Repeat Yourself, a principle formalized by Andy Hunt and Dave Thomas in The Pragmatic Programmer. It aims to reduce duplication in code, logic, and documentation.
Why DRY Matters
Duplicated code multiplies bugs: fix a bug in one place but miss the duplicate, and the bug persists. It also increases maintenance effort — every copy is another place to update when requirements change. DRY reduces the surface area for bugs and the cost of change.
Real-World Analogy
Your phone number written on a whiteboard, a sticky note, a document, and a napkin. When you change your number, you must update all four places — miss one, and someone calls the wrong number. DRY says write it in one central place (address book) and reference it everywhere else.
Example: DRY Violation vs Fix
# Violating DRY — validation logic duplicated
def create_user(name, email):
if not name: raise ValueError("Name required")
if not email: raise ValueError("Email required")
if "@" not in email: raise ValueError("Invalid email")
print(f"User {name} created")
def update_user(user_id, name, email):
if not name: raise ValueError("Name required")
if not email: raise ValueError("Email required")
if "@" not in email: raise ValueError("Invalid email")
print(f"User {user_id} updated")# Following DRY — single validation function
def validate_user(name, email):
if not name: raise ValueError("Name required")
if not email: raise ValueError("Email required")
if "@" not in email: raise ValueError("Invalid email")
def create_user(name, email):
validate_user(name, email)
print(f"User {name} created")
def update_user(user_id, name, email):
validate_user(name, email)
print(f"User {user_id} updated")Related Terms
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro