Loading...
Loading...
Use when writing similar code in multiple places. Use when copy-pasting code. Use when making the same change in multiple locations.
npx skill4agent add yanko-belov/code-craft dont-repeat-yourselfNEVER duplicate logic. Extract and reuse.// ❌ VIOLATION: Duplicated validation
function validateRegistrationEmail(email: string): boolean {
return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
}
function validateProfileEmail(email: string): boolean {
return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email); // Same logic!
}
// ✅ CORRECT: Single source of truth
function validateEmail(email: string): boolean {
return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
}
// Reuse everywhere
const isValidRegistration = validateEmail(regEmail);
const isValidProfile = validateEmail(profileEmail);// ❌ Bug in tax calculation requires changes in 3 files
// cart.ts: const tax = price * 0.08;
// checkout.ts: const tax = price * 0.08;
// invoice.ts: const tax = price * 0.08;
// ✅ Single source of truth
// tax.ts: export const calculateTax = (price: number) => price * TAX_RATE;// ❌ VIOLATION: Similar functions with minor differences
function formatUserName(user: User): string {
return `${user.firstName} ${user.lastName}`;
}
function formatAdminName(admin: Admin): string {
return `${admin.firstName} ${admin.lastName} (Admin)`;
}
// ✅ CORRECT: Parameterized
function formatName(person: { firstName: string; lastName: string }, suffix?: string): string {
const name = `${person.firstName} ${person.lastName}`;
return suffix ? `${name} (${suffix})` : name;
}| Type | Example | Solution |
|---|---|---|
| Code | Same function body twice | Extract function |
| Logic | Same algorithm, different names | Extract and parameterize |
| Data | Same constant in multiple files | Centralize constants |
| Structure | Same class shape repeated | Extract interface/base |
| Knowledge | Business rule in multiple places | Single source of truth |
| Symptom | Action |
|---|---|
| Copy-pasting code | Extract shared function |
| Same validation twice | Create validator module |
| Same constant in files | Create constants file |
| Similar functions | Extract + parameterize |
| Bug fix needs multiple changes | Consolidate to one place |
| Excuse | Reality |
|---|---|
| "It's faster to copy" | It's slower to maintain duplicates. |
| "They're slightly different" | Extract common, parameterize differences. |
| "Just a few lines" | Few lines × many places = many bugs. |
| "I'll refactor later" | You won't. Extract now. |
| "Different contexts" | Same logic = same code, regardless of context. |
| "More readable as copies" | Named, extracted functions are more readable. |