I'm building an app for android which allows objects to be merged together based on certain conditions. At the moment I'm looking to do this using if statements (nested or not) and am just wondering if there is a better way to do this so it is more flexible and easily expanded.
For example, I have 6 objects, 3 of them are red, 2 are blue and 1 is green.
The rules that can be applied to that are:
That is a very basic example of it. There will be a lot more than that.
I would probably do something in region of:
Create a Rule-class, that holds the logic for a given rule (your if-statements). A Rule should have a priority, so that it can be matched up against other rules to determine what rule should be considered first. It also needs a method to which an undetermined number of objects can be passed to, which checks if these objects fulfill the rule.
Create a RuleEngine, which holds a sorted list (by priority, highest first) of all rules. You then pass the objects you want to match towards the rules to the engine and the engine runs through them, breaking the loop if a rule is fulfilled:
for( Rule rule : rules ) {
if( rule.check( objects ) ) {
//Do what needs to be done
break;
}
}
I don't know if this makes sense to you - I hope it does.
Also if we're talking thousands of rules this solution is not optimal. In that case you would want to determine which rules the object might have a chance to fulfill before checking them (e.g. if you have two red and one green, there's no need to check the 'one-of-each'-rule).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With