Back to code. It seems like everytime we use the Query instance, we
have to configure it. The problem however is that Query is
something we don’t get access to until we hit that line of code
which unfortunately is within that BaseVHDao class and specifically in the BaseVHDao#list method.
That leaves us with no option but to configure it right there with little room for extending or
reusing that configuration as we are limited to:
There are 2 advantages of using delegation in this case.
Don’t have to expose Query to client code
It is easily extensible
Since we need to support different configurations we introduce a
simple interface like
Java Note: By making the QueryStrategy typed as well notice how we enforce a strong typing with the CRUDService. That way we effectively only pass valid QueryStrategy(ies)
Now what about args and clazz that we also need to have available? Let’s add them to that interface.
That looks great. However, what started as a one method interface to configure the query ended up somewhat “stiff” should we wish to extend a QueryStrategy for the
same type and arguments. So let’s add the final piece in the puzzle. (Disclaimer)
In case you can’t see the relationship between them, it’s composition. Let me make it clearer.
Disclaimer In this example it’s not that big of a deal but it’s good to keep an eye for things that might change and draw your lines early. The good thing is that even if you don’t add the extra interface right now, your API is designed to accept that change without affecting the client and with minimal refactoring cost.