I have a List of interface type Criteria within my class Query.
List<Criteria> criteria = new ArrayList<Criteria>();
I have several concrete implementations of Criteria. I want to give Query a method that iterates through my criteria list, and depending on the concrete type, execute some logic.
I’m presently doing this with instanceof like so:
for(Criteria c : criteria) {
if(c instanceof ContextualCriteria){
// logic
}
...
}
Is this the only/best way?
Does the logic sensibly belong in the
Criteriaitself? If so, put it into theCriteriainterface and implement it appropriately for each concrete class implementing theCriteriainterface. This is obviously the nice polymorphic approach.Unfortunately, in real life OO doesn’t always work as simply as that – sometimes it doesn’t make sense to put the per-type behaviour in the type itself, so you may need to use
instanceofinstead. You could potentially have a map from “criteria class” to some interface representing the action to take, but that could easily end up being even messier.Double-dispatch via the visitor pattern can sometimes improve things a little – so the logic could still be in separate methods in your “calling” class, but each
Criteriacan call back to the right method via a single interface method. Personally I tend to find this increases coupling and gets ugly quickly, but others swear by it.