interface Resolver {
boolean canResolve(SomeInput input);
SomeOutput resolve(SomeInput input);
}
public static void main(String[] args) {
List<Resolver> resolvers = ...;
SomeInput someInput = ...;
SomeOutput someOutput = resolvers
.stream()
.filter(res -> res.canResolve(someInput))
.findFirst()
.map(res -> res.resolve(someInput))
.orElseThrow(() -> new IllegalStateException("No suitable handler found."));
}
This solution is inspired by HttpMessageConverter
interface in Spring. I'm not sure if there is any official name for this pattern.
Is it a bad practice to have such coupling (resolve
should be called ifcanResolve
returned true) between two methods of an interface? Is it acceptable if these resolvers are guaranteed to be used only from one place?
Other option I considered is to have one interface method only returning Optional
, it would return empty Optional
if it can't handle the input. This eliminates coupling but on the usage side it's not as readable as the previous one.
interface Resolver {
Optional<SomeOutput> resolve(SomeInput input);
}
A third option could be Chain of Responsibility design pattern but that seems a bit overkill for this simple thing.
Does the first option have any other drawback? Is there any other solution that nicely fits this use case?