In JavaScript (ES6), I can have optional function parameter with default value. So to add a new behavior to the existing code base, I could either introduce new method(s) or extend the existing method with an optional parameter.
Consider the following example:
Existing method:
doSomething(param) {
// code to do something trivial
}
Desired new behavior: the ability to do something special after doing something trivial
Option 1: extend the existing method
doSomething(param, isSpecial = false) {
// code to do something trivial
if (isSpecial) {
// code to do some more thing special
}
}
Usage:
doSomething(param); // do something trivial
doSomething(param, true); // do something special
Option 2: add a new method
doSomethingSpecial(param) {
doSomething(param); // just call the existing method to do something trivial
// code to do some more thing special
Usage:
doSomething(param); // do something trivial
doSomethingSpecial(param); // do something special
Option 3: extend the existing method and add two new methods
doSomething(param, isSpecial) {
// code to do something trivial
if (isSpecial) {
// code to do some more thing special
}
}
doSomethingTrivial(param) {
doSomething(param, false);
}
doSomethingSpecial(param) {
doSomething(param, true);
}
Usage:
doSomethingTrivial(param); // do something trivial
doSomethingSpecial(param); // do something special
Currently I'm mostly using the first option, because it's less code to write. But thinking of the open closed principle, it doesn't sound right for me.
So which option should I choose? (in general, not special in JavaScript)