I have been reading some articles about the open-closed principle and all seem to be related to OOP.
Is there a way to do open-closed principle in functional programming using Node.JS for example?
CodePudding user response:
Sure, indeed FP is all about reusing functions to build new ones.
For example:
You can declare a function add :: Number -> Number -> Number
const add = (x) => (y) => x y
And then use add
to build another function like mult :: Number -> Number -> Number
const mult = (x) => (y) => y === 0 ? 0 : x mult(x)(y - 1)
Each function could be considered atomic, as there's no need to do further changes. So, by this way you don't modify previous functions, you re-use them to form new ones.
CodePudding user response:
There's several ways to achieve this principle, for example if you create classes, you can inherit the functions and then extend its functionality. For example:
class NumberConverter {
isNumber(number) {
return true;
}
convertBase(number, fromBase, toBase) {
return parseInt(number, fromBase).toString(toBase);
}
}
class DecimalToBinary extends NumberConverter {
isDecimalNumber(number) {
return true;
}
dec2bin(number) {
return this.convertBase(number, 10, 2);
}
}
You can see how you can extend the convertBase
and extend its functionality. You can extend from multiple classes just adding a comma after each class like extends Products, Music
.
But if you want to create another kind of approach, you can do composition instead of inheritance, meaning that with the previous example, you can make a new class like so:
class Calculator {
properties;
numberConverter;
setDecimalConverter(numberConverter) {
this.numberConverter = numberConverter;
}
convertDec2bin(number) {
return this.numberConverter.convertBase(number, 10, 2);
}
}
So then you can use the new class Calculator
like this:
const calculator = new Calculator();
calculator.numberConverter = new NumberConverter(); // If you don't want to do this, you would have to add the NumberConverter in the Calculator constructor
calculator.convertDec2bin(5);
And all of this functionality can be done as a function. (Although it might not be exactly an open-closed principle, I think it still solves your use case). You can use it like this:
const Calculator = function(NumberConverter) {
const numberConverter = NumberConverter;
return {
convertDec2bin(number) {
return numberConverter.convertBase(number, 10, 2);
}
}
}
const calculator = Calculator(NumberConverter());
calculator.convertDec2bin(5)