Function "normalization"
Here's a concept from the DB normalization theory:
Third normal form is violated when a non-key field is a fact about another non-key field.
Doesn't it makes sense for a similar concept be applied for functions / function parame开发者_Python百科ters?
Consider the following function:
function validate(field, rule_name, rule_value);
// Usage
validate("password", "min_length", 6);
validate("password", "matches_regex", "/^\S+$/");
In this example function, the third parameter describes the second and seems to have no "attitude" towards the first. It feels like a denormalized function in a way.
I don't know if I'm formulating this right, but I can notice an analogy between table names and table fields, in the DB, and function names and function parameters.
If such analogy makes sense, wouldn't it also make sense for function designers to borrow concepts from the DB normalization theory?
To me that function does suggest some sort of "rule" concept that is parametrized by a value. It could be made more generic if you could have a list of such rule/value pairs and validate by looping over all the rules.
Looking at it another way, nothing seems to be lost if you interpret the functions as follows:
function validate(field, rule);
// Usage
validate("password", MinLengthRule(6));
validate("password", RegExRule("/^\S+$/"));
Consider the OOP variant of your example, when using the Strategy design pattern. In that case it would be natural (to me, at least) for the rule name to be an attribute of the Rule
class, which would support your idea.
Don't agree. The 6
doesn't describe min_length
. Only both create something meaningfull.
The garbage characters doesn't mean anything neither until you notices it is a regexp.
精彩评论