A recurring scenario is annoying me. The scenario is this: Create a value object, in the Domain-Driven Design sense, and use it in a Hibernate persisted domain model. Following the DDD style, a value object shouldn’t have a default constructor, because its state should be present upon it’s creation as arguments to its constructor. It should be immutable and have no setters for its state. This won’t work if you’re using any tools/frameworks that require default constructors on the objects in your domain model. I know that with Hibernate you can use non-public (package protected is recommended) constructors to limit the ‘damage’, but there is still an opening for mis-use of the value objects.
There are ways around it, like creating proxy objects for the tools/frameworks, but that, too, can be a lot of work and can negate some of the productivity savings you get by using the frameworks. It’d be cool if in frameworks like Hibernate they’d offer you an option to use a factory creation method or a similar scheme. I’m not close enough to the source to know how feasible this is in Hibernate specifically, but from a generic standpoint, this could be pretty easily done and specified in configuration.
I wonder if I’m missing something on this. How do others follow the value object principle without giving in to the practical needs of tools and frameworks that they use. Take a look at the TimeAndMoney Domain Classes (Basically a reference implementation for DDD). They are loaded with rants about some methods/constructors that are only included for ORM solutions and how they break encapsulation.
Leave a Reply