DEV Community

Rishabh Joshi
Rishabh Joshi

Posted on

Duplication vs. Coupling: When do you actually refactor duplicate code in Python?

When building and maintaining larger Python codebases, one of the classic debates between senior engineers is balancing the DRY (Don't Repeat Yourself) principle against premature coupling.

Consider a situation where two or three separate modules have identical 10-line boilerplate (for example, database connection lifecycle handling, recurring input validation checks, or retry logic):


python
# Seen across module_a.py and module_b.py:
managed: bool = conn is None
if managed:
    conn = init_db(DB_PATH)
try:
    yield conn
finally:
    if managed:
        conn.close()
Enter fullscreen mode Exit fullscreen mode

Top comments (0)