Sunday, 18 March 2018

Domain Driven Design Lazy Loading

Lazy loading sounds straightforward, but DDD manages to complicate things. DDD states that entities should not hold references to services or repositories. That is really not debatable, and people that have even the most basic understanding of DDD will follow this rule without questioning it. So if that is the case, then how do you lazy load, because the entity has to call something to get the data. This is a discussion I had with my good friend Daniel Mouritsen and it seems that a friend of his even stalked poor Eric Evans to get an answer. Now I can't promise that Eric Evans will be happy with my solution, so it's upto you to decide. 

An example

Let's take a very simple example. We have a User entity and a Wallet entity. The users can have multiple wallets. A user entity can look for an user by id, but we don't want to load the wallets eagerly, we want to load the wallets only if something actually tries to access them.

Functional to the rescue

While we're not allowed to hold references to other services or repositories in our entities, how about a Java 8's Supplier? This will not create a direct dependency between the User and the Wallet repository, the User class has no idea that the Wallet Repository even exists. So the User changes slightly:

What that means is that we can set the wallets as a lambda expression and most importantly, that lambda expression is not called unless we are accessing the wallets. And here's what we need to do in the repository:

Pretty straightforward, right? The full example is available here.
If you liked this, don't forget to share!

No comments:

Post a Comment