Domain-Driven Design – How to Persist an Aggregate Containing Polymorphism

domain-driven-designopen-closed-principle

I've been developing applications according to the principles of DDD for a while now, and, as many, I often run into issues when it comes to persisting an aggregate.

One of the main advantages of DDD is that it allows me to use the full power of OO design in my domain — as such I want to use polymorphism and conform to the open-closed principle. I.e. I can extend my logic by adding new subtypes without requiring changes to the supertypes.

enter image description here

The problem comes when persisting this. Somehow I need to flatten this domain to some persisted representation, and then later restore it. How do I achieve this, without littering the Repository implementation with instanceof (or equivalent in your language of preference) all over the place. This is generally considered bad form, plus it violated OCP, at least in the repository itself. When I add a new subtype, I'm forced to add a case in the repository.

Is there an elegant way to handle this?

Best Answer

Mark Seeman provides the simple answer to your immediate pain point: at the boundaries, applications are not object oriented.

You might also read Greg Young's essay The Generic Repository.

One of the main advantages of DDD is that it allows me to use the full power of OO design in my domain -- as such I want to use polymorphism and conform to the open-closed principle.

You might need to let that go - there's not a lot of prior art encouraging the use of inheritance in constructing the domain model.

Composition, rather than inheritance, is the more commonly discussed pattern of re-use.

My suggestion: if you really think that you need inheritance, step back for a bit and challenge your domain model; it may be that the ubiquitous language is trying to show you that there are isolated concepts that your current perspective conflates.