I have a requirement where there are 10 Rules to be applied on data in excel. If Rule 1 and Rule 2 fails rest of the rules are not checked. But if Rule 1 and Rule 2 passes the rest of all the Rules should be verified and if any errors found- they should be logged. Is there any design pattern which I can use to keep this Rule Engine flexible for adding these 10 rules and Closed for any additional chains in the Current Rule. I was thinking of something like a Decorator Pattern. Will this help me achieve that?
migrated from stackoverflow.com Oct 30 '12 at 14:28
|
If your rules look something like this:
Then applying them looks something like this:
You can implement as many rules as you wish. |
|||
|
|
|
Thinking out loud here. Imagine you have different states and commands. For example:
You can represent those are enums or classes. You then have commands:
Commands can be classes that would encapsulate some logic and have a single "run" method. You can then start modelling your rules by selecting states and assigning appropriate commands to those states. I was always excited about using patterns and best practices, but unless you can think of the right pattern for the job in first few minutes, than you are probably over-engineering something. |
|||
|
|
|
If you are using .Net Framework for this solution, I would suggest using External RuleSet Toolkit Sample from Windows Workflow Foundation. It has rule chaining and a nice redistributable rule editor GUI. |
|||
|
|
|
The best way to do it is to not do it. Designing for ultimate flexibility for some unknown future requirements is one of the great pitfalls in software engineering. Allowing any arbitrary rule from business into the design is another of the great pitfalls. If you only have 10 rules, and are working on some podunk excel processing app... just hard code the rules. You'll do it faster, in a way that is easier to debug, maintain, and extend (unless you're going to be adding/changing a new rule every week or so). |
|||||
|
|
I think a combination of Composite and Chain of Responsibility could fit:
Successors in the chain are evaluated only if the first rule passes, and composites' leaves are always invoked (with an appropriate aggregate for the composite result, e.g. |
|||
|
|
|
It's a good approach to try and find a best practice for doing something, particularly in a design pattern. But sometimes finding a 'pattern' or understanding all of them to know which to apply can consume time. Is applying a pattern here necessary, from your 'question' above, you could knock out the 'code' quicker than coming to a conclusion on a pattern/potential pattern (the apparent logic doesn't sound difficult) Nevertheless, if it is your consideration to use one, I would suggest the State Pattern. http://en.wikipedia.org/wiki/State_pattern (It's similar to the Strategy Pattern) The State pattern allows an object to behave differently based on it's state. |
|||||
|

