Interview Q&A / Object-Oriented Programming

IntermediateQuick answer1 min readUpdated 3 Oct 2026

Show the Open/Closed Principle in JavaScript with a list of validation rules.

SHORT ANSWER

Keep rules as a list of small functions and run them all with one loop. A new rule is added by appending a function, and the validating code is never changed.

Explain it simply

A bouncer with a checklist: age proof, ticket, no bags. To add a rule, you add a line to the checklist and the bouncer's way of working stays the same.

The validating function loops over whatever rules exist. It does not know or care how many there are.

Example

js
const rules = [
  (pw) => pw.length >= 8,
  (pw) => /\d/.test(pw),
];

function isValid(pw) {
  return rules.every((rule) => rule(pw));
}

console.log(isValid("abc"));        // Output: false
console.log(isValid("abcdefg1"));   // Output: true

rules.push((pw) => /[A-Z]/.test(pw));   // new rule, no edit to isValid
console.log(isValid("abcdefg1"));   // Output: false

The same idea appears as middleware in Express, plugins in editors, and event listeners in browsers.

What to say in the interview

"I model each rule as a function in a list and iterate over it. isValid stays the same when rules are added, which is OCP in a functional style. The same idea shows up in middleware and plugin systems."

Common mistakes

  • Hard-coding each rule as another if inside the validator.

#solid#ocp#javascript

Related questions

Practise more Object-Oriented Programming questions

Test your recall with short answers, then return to the detailed explanations when you need context.

Open Object-Oriented Programming quick answers →

Get new questions like this by email

One short email when something new and useful lands. No spam, unsubscribe in one tap.

By subscribing you agree to the Privacy Policy.