Context:
I have a list of objects and I want to apply a set of rules on them. For any object, once a rule can be applied, it will be applied and the subsequent rules won't be applied. I wanted a design that provided very little coupling and great flexibility to add or delete rules.
Right now, there are a number of "rules" functions that take the object and return a boolean saying whether the rule was applied or not, example:
def rule1(obj):
if obj.x > 1:
#here we apply some action on the object...
return True
return False
And I have an array holding the functions(rules) that are to be applied on each object:
rules = [rule1, rule2, rule3]
And the logic looks like this:
for obj in object_list:
for rule in rules:
success = rule(obj)
if success:
break
Problem:
One of the rules actually depends on what happens on a previous rule and thus needs some data from the other rule. I want to keep the loose coupling I already have and the possibility of changing the order of the rules(for example by adding an intermediate rule between the two linked rules...). Also, in the future, I'll probably want to apply the rules on my objects in parallel so any solution should (ideally) keep this in mind.
What's the best solution/tradeoff for this problem? By the way, here I represented the rules as functions but they could be represented as classes, for example, if it's easier to solve this problem. Thanks for your help :)
Aucun commentaire:
Enregistrer un commentaire