Reputation: 10064
I find I use the following pattern when I have a known execution path between several conditionals. I will define my test cases in a Map (in this example a POJO) and use the conditionals to make a key lookup. I've typically used the term predicate
.
Is there a standard name to this pattern and if so what is the history or context around its use?
var predicates = {
negateRegexp: function (value, operator) {
return !operator.regex.test(value);
},
negateOperand: function (value, operator) {
return value !== operator.operand;
},
affirmRegexp: function (value, operator) {
return operator.regex.test(value);
},
affirmOperand: function (value, operator) {
return value === operator.operand;
}
};
var predicateKey = (operator.prefix === '!' ? 'negate' : 'affirm') +
(operator.regexp ? 'Regexp' : 'Operand');
var testResult = predicates[predicateKey](value, operator);
if (testResult) {
doSomethingWith(value);
}
I used JavaScript for the example as that is what I usually work in. But I'm sure I've seen this pattern in other languages (even OOP-typed ones like Java)
Upvotes: 3
Views: 57
Reputation: 664196
In OOP, this is known as the strategy pattern. Given the lookup table, it also resembles the interpreter pattern however for a really simple language in your case. Using strategies for causing side effects might also be known as the command pattern, but I'd argue that's not the case in your example.
In FP, this pattern doesn't have a specific name, it's just how you do things - although the lookup method might be called a higher-order function as it returns another function.
Btw, the term predicate usually means just a function that returns a boolean, while this fits in your case it doesn't have anything to do with the abstraction pattern.
Upvotes: 3