๐Ÿ“ Programming

DRY: Don't Repeat Yourself ๐Ÿ”„

P
Author
PyLand Team
๐Ÿ“…
Published
03.04.2026
โฑ๏ธ
Reading time
4 min
๐Ÿ‘๏ธ
Views
400
๐ŸŒฟ
Level
Medium

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! ๐Ÿš€

Your reaction to the article

๐Ÿ’ฌ Comments (0)

๐Ÿ” Sign in to leave a comment
๐Ÿšช Login
๐Ÿ’ญ

No comments yet

Be the first to share your opinion about this article!

๐Ÿ”— Similar

Similar articles

Continue learning with these materials

๐Ÿ“

KISS: Write Simply, Write Clearly ๐ŸŽฏ

Does your code work? Great! But there's one more important criterion โ€” readability. Code is...

๐Ÿ“… 03.04.2026 ๐Ÿ‘๏ธ 369
๐Ÿ“

Functions: Best Practices

Goal: Write functions that are easy to read, test, and reuse.

๐Ÿ“… 03.04.2026 ๐Ÿ‘๏ธ 409
๐Ÿ“

Clean Code and Useful Comments ๐Ÿงน

Imagine a workbench after a large project: the tools are useful, but empty boxes and...

๐Ÿ“… 03.04.2026 ๐Ÿ‘๏ธ 389