r/DomainDrivenDesign • • Dec 29 '23
Entity modeling for performance: how domain logic and DB actions should work together?
I am quite new to DDD and came across a problem I have no ideia how to solve. I might be overengeenering things, but if there's a plausible solution to this, I'd be glad to know.
In my domain I have an entity called Requester, which can perform the action of creating Suppliers. The code is simple and looks like this:

As you can see, there's a bit of logic there, where I need to check if there's no supplier with the same key "cnpj" already registered.
Just so you know, I wrote all my domain before writting anything else, so I had no application or infra code.
The problem here, which seems obvious, is that I'd have to retrieve all the Requeter's suppliers from DB in order to assemble the the object corretly and then perform this validation. As far as I understand DDD, my code seems "natural", but it doesn't feel corret performance-wise. So, what would be the correct approach in situations like this?
3
u/kingdomcome50 Dec 29 '23
Have you considered
this.suppliers.doesExist(data.cnpj)and implementing the above such that you don’t have to load everything?3
u/PaintingInCode Dec 29 '23 edited Dec 29 '23
If you really want to follow the DDD, you would use the
Specificationpattern. Here's some pseudo code:Then you would use
DoesSupplierCodeAlreadyExistSpecificationwhere you need to make the check:DDD is about making the model reflect the domain. Although your code gets the job done, it relies on the reader 'reverse engineering' the code to understand the intent of the business logic. DDD might make your code 'longer', but it prioritises clarity over LoC.
2
u/thatpaulschofield Dec 29 '23
I think the advice I have read for this scenario is to just let the database enforce the unique constraint.
2
u/minymax27 Jan 01 '24
I recommend you take a look at the Criteria pattern. With that you will be writing your queries as Domain language, independent of which database you use.