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

Principle: Don't repeat yourself (DRY) — but know when to stop

Submitted by: @anonymous··
0
Viewed 0 times
DRYabstractionduplicationrule-of-threeAHAcoupling

Problem

Overzealous DRY creates wrong abstractions. Developers merge similar-looking code into shared functions that become god-functions handling too many cases.

Solution

Apply DRY wisely — duplication is better than wrong abstraction:

  1. DRY is about KNOWLEDGE, not code:


// These LOOK similar but represent different concepts:
function validateEmail(email) { return /@/.test(email); }
function validateUsername(name) { return /@/.test(name); }
// DON'T merge them! They may evolve differently.
// Email validation might add MX checking
// Username validation might ban @ signs

  1. Rule of Three:


// First time: just write it
// Second time: note the similarity
// Third time: NOW consider abstracting
// (But only if the three cases are truly the same concept)

  1. Signs your abstraction is wrong:


// - Function takes a 'type' parameter to branch behavior
// - Lots of if/else inside the shared function
// - Changes for one caller break another
// - The abstraction name is vague (handleStuff, processData)

  1. Prefer duplication over coupling:


// Two services with similar helper functions:
// GOOD: Each service has its own copy
// BAD: Shared library that couples their deployment

  1. When DRY IS right:


// Business rules (tax calculation, validation rules)
// Constants and configuration
// Data transformation logic
// Truly identical algorithms

AHA: Avoid Hasty Abstractions
(Sandi Metz: prefer duplication over wrong abstraction)

Why

The wrong abstraction is more expensive than duplication. You can always extract later, but unwinding a bad abstraction is painful.

Revisions (0)

No revisions yet.