DRY — Don't Repeat Yourself: the principle and the pitfall of over-applying it
Definition
DRY — Don't Repeat Yourself — is the principle that every piece of knowledge in a system should have a single, authoritative representation. When a business rule, algorithm, or fact exists in more than one place, a change to that knowledge requires finding and updating every copy, and missing one creates bugs. DRY is not simply about avoiding copy-pasted code; it is about consolidating knowledge, which is a subtler and more demanding standard.
In Practice
<?php
// VIOLATES DRY: the "a user is active" rule is in three places
class UserController
{
public function show(User $user): JsonResponse
{
if ($user->status === 'active' && $user->email_verified_at !== null) {
// ...
}
}
}
class OrderService
{
public function placeOrder(User $user, Cart $cart): Order
{
if ($user->status === 'active' && $user->email_verified_at !== null) {
// ...
}
}
}
// FOLLOWS DRY: one authoritative definition
class User extends Model
{
public function isActive(): bool
{
return $this->status === 'active' && $this->email_verified_at !== null;
}
}
// Both callers now use the single source of truth
if ($user->isActive()) { /* ... */ }DRY applies beyond code: database schema (don't store a calculated value that can be derived), configuration (one canonical .env file, not values scattered across config files), and documentation (a single README, not duplicated setup instructions). In Laravel, Eloquent scopes, shared middleware, and base Form Request classes are all mechanisms for keeping knowledge DRY.
In Context
In interviews, DRY comes up in code review prompts where you are shown repeated logic. The expected response is to name the duplication, explain which place should own that logic, and describe the extraction. Be prepared to also know when not to DRY — two pieces of code that look the same but represent different business concepts should stay separate; premature consolidation creates wrong dependencies.
The classic pitfall is over-applying DRY. The "wrong abstraction" anti-pattern (coined by Sandi Metz) describes the pain of having extracted code too eagerly: callers begin to diverge, the shared function accumulates boolean flags to handle each case, and the result is worse than the original duplication. The rule of three is a practical heuristic: tolerate one copy, consider extraction at two, extract definitively at three.
Related terms: WET (Write Everything Twice — the humorous opposite, sometimes used as a deliberate stance), abstraction (the mechanism you create when you DRY something up), YAGNI (the companion principle: don't add abstractions for hypothetical future reuse), and coupling (bad DRY extractions create wrong dependencies between unrelated modules).