Asher Cohen
Back to posts

Descriptive Conditionals: Making Code Self-Documenting

Extract complex conditional expressions into named functions for clearer, more maintainable code

Introduction

Conditionals are fundamental to programming, but complex conditional expressions can make code hard to read. The solution? Extract them into named functions that explain their intent.

The Problem with Inline Conditionals

// ❌ What does this check?
if (score === 100 || remainingPlayers === 1 || remainingPlayers === 0) {
  quitGame();
}

You have to read and understand the entire expression to know what it's checking for.

The Solution: Named Conditionals

Extract the conditional logic into a well-named function:

// ✅ Clear intent
const winnerExists = () => {
  return score === 100 || remainingPlayers === 1 || remainingPlayers === 0;
};

if (winnerExists()) {
  quitGame();
}

Now the intent is immediately clear from the function name.

Benefits

Self-Documenting Code

// ❌ Unclear business logic
if (user.age >= 18 && user.verified && user.subscription === 'premium') {
  grantAccess();
}

// ✅ Self-documenting
const canAccessPremiumContent = (user) => {
  return user.age >= 18 && user.verified && user.subscription === 'premium';
};

if (canAccessPremiumContent(user)) {
  grantAccess();
}

Easier Testing

test('canAccessPremiumContent returns true for eligible users', () => {
  const eligibleUser = {
    age: 25,
    verified: true,
    subscription: 'premium',
  };

  expect(canAccessPremiumContent(eligibleUser)).toBe(true);
});

Reusability

// Use the same logic in multiple places
if (canAccessPremiumContent(user)) {
  showPremiumFeatures();
}

const premiumUsers = users.filter(canAccessPremiumContent);

Best Practices

Name Based on Intent, Not Implementation

// ✅ Describes what
const isEligibleUser = (user) => {
  return user.age >= 18 && user.active;
};

Keep Conditionals Focused

// ✅ Specific
const hasRequiredFields = (data) => {
  return data.name && data.email && data.age;
};

Use Descriptive Parameter Names

const isWithinBudget = (expense, budget) => {
  return expense.amount <= budget.limit;
};

Conclusion

Named conditionals transform cryptic boolean expressions into self-documenting code. Extract complex conditionals into well-named functions—your future self will thank you.

clean-code #javascript #best-practices