3 ms·
// stateful impl class foo{ enum current_operator; init() { current_operator = ADD } evalOp(int a, int b){ if (current_operator == ADD) r
by lalos 6y ago
// stateful impl
class foo{
enum current_operator;
init() { current_operator = ADD }
evalOp(int a, int b){
if (current_operator == ADD) return a + b;
else if (current_operator == MULTIPLY) return a * b;
}
setOp(enum op){ current_operator = op; }
}
// pure impl
class bar{
evalOp(enum op, int a, int b){
if (op == ADD) return a + b;
else if (op == MULTIPLY) return a * b;
}
}
In the first case, evalOp is not pure since one has no idea on what is the current_operator set as. In the second case it is pure since the operator is part of the input.
Purity refers to reproducibility, as in no matter what else is going on, that function will always behave the same. You can have pure functions in OOP based languages, but in practice devs just default to managing state and having weird behavior depending on outside state of a given function.
As a side note, and since you mention runtime performance cost: if you implement a dummy generic cache layer and you have pure functions you will have an easier time than having stateful impls. In this case, that cache layer must have the ability to introspect into foo, but in bar that cache layer just keeps track of input and that's it.
- TeMPOraL 6y agoTangential: Pure impl v2: class foo { public: //enum is a keyword, so let's call it _enum const _enum current_operator; foo(_enum co) : current_operator(co) { } // ... evalOp() as in your stateful impl example ... }; //Example use: Reduce(foo{ADD}, 1, 2, 3, 4, 5, 6); Point being, functional purity doesn't necessarily mean only functions taking all their inputs as arguments. It means no mutable state. In the above example, the class foo essentially represents a partially applied evalOp(). If you have multiple, related functions working on similar sets of parameters, you could put them in such a class with const members to create what is essentially a package of partially applied functions.