Code Quality

Duplicate Code in JavaScript: Applying the DRY Principle

When the same logic exists in multiple places, bugs are fixed in one place but forgotten in others. Behavior diverges over time.


❌ Duplicated Validation

function createUser(name, email) {
  if (!name || name.length < 2) throw new Error('Name too short');
  if (!email || !email.includes('@')) throw new Error('Invalid email');
  return db.insert('users', { name, email });
}

function updateUser(id, name, email) {
  if (!name || name.length < 2) throw new Error('Name too short');  // Duplicated!
  if (!email || !email.includes('@')) throw new Error('Invalid email');  // Duplicated!
  return db.update('users', id, { name, email });
}

✅ Extracted Validation

function validateUserFields(name, email) {
  if (!name || name.length < 2) throw new Error('Name too short');
  if (!email || !email.includes('@')) throw new Error('Invalid email');
}

function createUser(name, email) {
  validateUserFields(name, email);
  return db.insert('users', { name, email });
}

function updateUser(id, name, email) {
  validateUserFields(name, email);
  return db.update('users', id, { name, email });
}
💡

Pro tip: Install jscpd to get a report of all duplicated code blocks above a configurable threshold. Aim for zero clones above 10 lines.

Paste this code into LearnCodeGuide

Detect JavaScript vulnerabilities and bugs automatically with AI-powered analysis.

Analyze JavaScript Code →

Related Guides

Javascript Long FunctionJavascript Magic NumbersJavascript Dead Code