Published on 30 October 2012 by @mathiasverraes
Say we want to handle some commands. In classical OOP, we’d start by making a
CommandHandler, and give it one public method
handle(command). Our method is probably going to have some services it depends on, like a Repository. We inject that
repository as a parameter will automatically bring it into scope
Elsewhere, we create an instance of the
CommandHandler – for example when we set up a dependency injection container.
And again elsewhere, we call the
handle method on our instance.
all there’s the Noun.verb() combo. We’re really only interested in one method:
handle. Yet we have to have a class,
with an artificial name like
CommandHandler, which is just a there to bring us the
So let’s get rid of the class, and keep only the verb, aka the
handle() method. That means we now have to pass in the
Repository in some other way. We can pass it in as a parameter, but that’s awkward, because then we’d have to have the
Repository object available everywhere we want the
handle(), but that’s too much internal information for client code to know.
Functional programming has a neat little trick that can be applied here. A partial is function that takes another function, and ‘pre-fills’ a number of parameters. It returns a function that only needs the leftover parameters. Here’s a typical example:
Partials can easily be used to ‘configure’ a function in a DIC, and the use the pre-configured version of the function in the client code:
This looks nice. However, what you loose in cruft you also loose in clarity. In the class-based implementation, a new developer can simply look up the class definition to see the dependencies of a certain command handler. It seems to me that with this partial-function approach a new developer has to look at the handler implementation and the DIC to validate what stuff gets injected. Not sure if that’s a trade-off I’d be willing to make.
If you’re just writing client code, I don’t think there’s any added complexity.
In production code, you’d write something like
container.handleCommand(command) instead of
container.commandHandler.handle(command). I suppose you could do type hinting in an IDE
with annotations like JsDoc or Google Closure Compiler, so that should help reduce the clicking around.
But as I said, I’m stilling fooling around, I’m sure I’ll get a better feel for what is practical and what is not.
Follow @mathiasverraes on Twitter.
|Modelling Heuristics||Workshop @ Domain-Driven Design Europe||workshop||Amsterdam, NL||Feb 1|
|Conference||Domain-Driven Design Europe 2017||organiser||Amsterdam, NL||Jan 31 - Feb 3|
|Domain-Driven Design||Neos Conference||workshop||Hamburg, DE||Mar 30|
|Keynote (TBD)||Neos Conference||keynote||Hamburg, DE||Mar 31|
This work by Mathias Verraes is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 License.