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
check_host("192.0.2.10")
check_host("192.0.2.20")
check_host("192.0.2.30")
# After
targets = ["192.0.2.10", "192.0.2.20", "192.0.2.30"]
for target in targets:
check_host(target)
3. Use Parameters
Similar functions โ one function with parameters
# Before
def validate_short_password():
return validate_password("short-example")
def validate_long_password():
return validate_password("longer-example-password")
# After
def validate_password_value(password):
return validate_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 hash_password(password):
return password_hasher.hash(password) # one-way password hashing
def encrypt_message(text):
return message_cipher.encrypt(text) # reversible 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
pass
โ 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 database-specific logic
return run_database_task(target, algorithm)
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!