Show the Open/Closed Principle in JavaScript with a list of validation rules.
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
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: falseThe 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.