Imagine you’re writing code to hack 10 systems. You copy the hack_system() function 10 times. Then you find a bug — and you have to fix it in 10 places! 😱
There’s a principle that saves you from this nightmare: DRY.
🎯 What Is DRY?
DRY = Don’t Repeat Yourself
The core idea: Every piece of knowledge should have a single, unambiguous representation in a system.
In plain terms: one task = one piece of code.
🔴 The Problem: Code Duplication
Example 1: Copy-Paste in a Hacker Simulator
❌ Bad:
# Progress bar for scanning
print("Scanning...", end="")
for i in range(10):
print("█", end="", flush=True)
time.sleep(0.1)
print(" Done!")
# Progress bar for hacking
print("Hacking...", end="")
for i in range(10):
print("█", end="", flush=True)
time.sleep(0.1)
print(" Done!")
# Progress bar for bypassing the firewall
print("Bypassing firewall...", end="")
for i in range(10):
print("█", end="", flush=True)
time.sleep(0.1)
print(" Done!")
What’s wrong?
- ❌ The same code is repeated 3 times
- ❌ To change the animation, you have to update 3 places
- ❌ Easy to introduce a bug (e.g., forgetting flush=True in one place)
- ❌ Takes up a lot of space
✅ Good:
def progress_bar(text):
"""Show a progress bar for any operation"""
print(f"{text}...", end="")
for i in range(10):
print("█", end="", flush=True)
time.sleep(0.1)
print(" Done!")
# Use one function for all operations
progress_bar("Scanning")
progress_bar("Hacking")
progress_bar("Bypassing firewall")
What changed?
- ✅ Code written once
- ✅ Changes made in one place
- ✅ Easy to add new operations
- ✅ Fewer bugs
🟢 Example 2: Repeated Conditionals
❌ Bad:
def hack_easy_system():
if difficulty == "easy":
print("🟢 Hacking easy system...")
return True
return False
def hack_medium_system():
if difficulty == "medium":
print("🟡 Hacking medium system...")
return True
return False
def hack_hard_system():
if difficulty == "hard":
print("🔴 Hacking hard system...")
return True
return False
✅ Good:
def hack_system(difficulty):
"""Hack a system of any difficulty"""
colors = {"easy": "🟢", "medium": "🟡", "hard": "🔴"}
print(f"{colors[difficulty]} Hacking {difficulty} system...")
return True
🔵 Example 3: Repeated Data
❌ Bad:
# Data scattered across the code
print("Hacker: Neo")
print("Level: 5")
# Somewhere else
print("Name: Neo")
print("Level: 5")
# And yet again
print(f"{Neo} - level {5}")
✅ Good:
hacker = {
"name": "Neo",
"level": 5
}
# Use data from a single source
print(f"Hacker: {hacker['name']}")
print(f"Level: {hacker['level']}")
print(f"{hacker['name']} - level {hacker['level']}")
🛠 How to Apply DRY?
1. Use Functions
Repeated code blocks → function
# Before
result1 = (a + b) * 2
result2 = (c + d) * 2
# After
def double_sum(x, y):
return (x + y) * 2
result1 = double_sum(a, b)
result2 = double_sum(c, d)
2. Use Loops
Repeated calls → loop
# Before
hack_system("192.168.0.1")
hack_system("192.168.0.2")
hack_system("192.168.0.3")
# After
targets = ["192.168.0.1", "192.168.0.2", "192.168.0.3"]
for target in targets:
hack_system(target)
3. Use Parameters
Similar functions → one function with parameters
# Before
def hack_with_easy_password():
return try_password("1234")
def hack_with_medium_password():
return try_password("qwerty123")
# After
def hack_with_password(password):
return try_password(password)
4. Use Data Structures
Repeated variables → dictionary or list
# Before
target1_ip = "192.168.0.1"
target1_port = 8080
target2_ip = "192.168.0.2"
target2_port = 8080
# After
targets = [
{"ip": "192.168.0.1", "port": 8080},
{"ip": "192.168.0.2", "port": 8080}
]
⚠️ When Is It OK to NOT Follow DRY?
1. The Code Looks Similar but Has Different Logic
# These look alike but do different things
def encrypt_password(text):
return hash(text) # One-way encryption
def encrypt_message(text):
return caesar_cipher(text) # Two-way encryption
Don’t merge them just because they look similar — the purpose is different.
2. Merging Makes the Code More Complex
❌ Bad (too complex):
def universal_hack(type, target, method, password=None, key=None, algorithm=None):
if type == "system":
if method == "brute":
return brute_force(target, password)
elif method == "key":
return use_key(target, key)
elif type == "database":
# ...20 more lines of conditions
✅ Better:
def hack_system_brute(target, password):
return brute_force(target, password)
def hack_system_key(target, key):
return use_key(target, key)
def hack_database(target, algorithm):
# Separate logic
Sometimes several simple functions are better than one complex one.
📝 Checklist: Is Your Code DRY?
- [ ] Is there any copy-paste? (identical or near-identical blocks)
- [ ] Can repeated code be replaced with a function?
- [ ] Can repeated calls be replaced with a loop?
- [ ] Can similar functions be combined using parameters?
- [ ] Is repeated data stored in one place?
- [ ] Would merging the code make it harder to understand?
🎓 Summary
The DRY Principle: Don’t repeat yourself — write code once, use it many times.
Why?
- ✅ Fewer bugs (fix in one place)
- ✅ Easier maintenance (changes in one place)
- ✅ Less code (fewer lines)
- ✅ Easier to understand (less duplication)
How?
- Use functions instead of copy-paste
- Use loops instead of repeated calls
- Use parameters instead of similar functions
- Store data in one place
Remember: Good code reads like a book — no repetition, no boring filler! 📚✨
Next step: Combine DRY with the KISS principle — and your code will be near perfect! 🚀
💬 Comments (0)
No comments yet
Be the first to share your opinion about this article!