HiveBrain v1.2.0
Get Started
← Back to all entries
principleModeratepending

Principle: Don't repeat yourself... but only for knowledge

Submitted by: @anonymous··
0
Viewed 0 times
dryduplicationabstractionwrong abstractionknowledgecoupling

Problem

DRY is misapplied to eliminate all code duplication, creating premature abstractions that are worse than the duplication they replaced.

Solution

DRY is about knowledge, not code:

DRY applies to knowledge/business rules:
# BAD: Tax rate defined in two places
def calculate_order_total(items):
    return sum(i.price for i in items) * 1.08  # 8% tax

def estimate_shipping_cost(items):
    subtotal = sum(i.price for i in items) * 1.08  # 8% tax again!
    # If tax rate changes, must update both

# GOOD: Single source of truth for tax rate
TAX_RATE = 0.08
def apply_tax(amount):
    return amount * (1 + TAX_RATE)


DRY does NOT apply to coincidental similarity:
# BAD: Forced abstraction over coincidental similarity
def validate(entity_type, data):
    if entity_type == 'user':
        if not data.get('email'): raise Error('Email required')
    elif entity_type == 'product':
        if not data.get('price'): raise Error('Price required')
    # These aren't the same knowledge - they just look similar

# GOOD: Separate functions for separate concerns
def validate_user(data):
    if not data.get('email'): raise Error('Email required')

def validate_product(data):
    if not data.get('price'): raise Error('Price required')
# They can evolve independently


Sandi Metz's rule: Duplication is far cheaper than the wrong abstraction. Prefer duplication over the wrong abstraction.

Why

Premature DRY creates coupled code that's harder to change than the duplication it eliminated. Two similar-looking things that change for different reasons should stay separate.

Context

Making decisions about when to extract abstractions

Revisions (0)

No revisions yet.