Primarily technical blog on Lisp, .NET, C# development.

Thursday, December 27, 2007

DDD - Factories and Repositories

There is this chapter about factories and repositories. The first to create new entities or aggregates. The second to retrieve/store the entities from/to a database.

There is this mysterious middle ground where you don't have too many associations. Where you normalize but not too much. You create a complex query engine but impose some restrictions to what should be retrieved. I agree, and have been there before, where too many associations tend to cause a graph loading issue. It may appear as too many resources to load an entity by a filter, or even worse, as a lazy initialization - no session in NHibernate. It is very difficult to achieve this middle ground. There is a compromise involved in richness of the model and speed/memory/session handling. On the other hand, to avoid the use of the associations is a way to kill the domain model completely. Removing its meaning and making it just a set of disconnected types.

I developed this filter type of criteria that uses allows the client to use the model to retrieve objects using a very declarative syntax. With this approach, by encapsulating the ORM framework and abstracting its complexities, I can say we have 90% or more of all needs satisfied. And it seems like the way to go. But the use of traversal to navigate the domain model, implying in an underlying implicit querying mechanism to retrieve the objects, although powerful, brings us too much complexity in terms of the lazy initialization nightmare. We end up loosing too much time trying to figure out how to fix these infrastructure issues then working on the model. When the issue arises, I have to say.

I have a feeling that most of the problems we end up having could be solved by a more DDD approach in terms of the usage of aggregates to encapsulate a group of dependent related entities and maintain its invariants. That would simplify a lot the way we interact with the objects in all business logic code and at the same time it would help us to build more reliable user interfaces.


Alberto Brandolini said...

In my experience (maybe too short to draw conclusions) with DDD and Hibernate, we've found that aggregate boundaries were a good way also to determine guidelines for lazy loading, meaning that eager loading was allowed only inside the boundaries of an Aggregate.



Lukas Macedo said...

That's a very interesting line of thought. I tend to agree because this is something that is happening almost naturally in a system I am working on. It has a huge legacy database and we are writing new modules using NHibernate to handle the persistence. It turns out that without developing some logical rules about lazyness x eagerness, developers tend to remove lazy loading without considering domain model boundaries.

Regards and thanks for the comment!