What is correct by DDD – should I create map of two objects eg Map or should i use more meaningfull object that will contain this pair MoreMeaningfullName{Obj1, Obj2} ?
If using first approach, I don’t create unnecessary classes, but in 2nd approach I have meaningful object (to some extent).
4
First of all I would like to object “correctness by DDD”. Domain Driven Design is all about constructing model of domain and exposing it in your design using object-oriented programming. It is not a set of strict rules, rather list of guidelines and patterns.
I assume that both types (Obj1
and Obj2
) stored in the map are meaningful to domain. Otherwise this map is out of DDD scope.
Existence of map of Obj1
to Obj2
suggest that there is one-to-many relationship between Obj1
and Obj2
. So the first question that you should ask yourself is whether this relationship is meaningful for your domain. Or maybe this is just technical detail useful for some calculation.
In the former case DDD suggest that you should consider making this relationship explicit. Too many relationships in your model make it too complex. Therefore Evans in DDD book suggests:
- imposing traversal direction
- adding qualifier to reduce multiplicity
- limiting associations to only those really essential
So if you decide to place the relationship in your model, there are different ways to make relationship explicit, as suggested by OOP principles. One-to-many relationship might be represented as attribute in Obj2
(for traversal direction Obj1 <-- Obj2
or collection of objects of Obj2
in Obj1
(for Obj1 --> Obj2
). You can also introduce some class representing association, which is especially useful for many-to-many relationships.
Of course if the map has its own identity or lifecycle, i.e. fulfils requirements for Entity, than it is recommended to model it as a separate class. I can also imagine a map being modelled as Value object, but see my remark below.
Even if the relationship is not meaningful or not essential for your domain, basic design principles still apply to your design (according to priority):
- Passes all the tests.
- Express every idea we need to express.
- Contains no duplication.
- Minimized the number of classes, methods and other moving parts.
So if you are going to duplicate some operations on the map in multiple places – create a class. If the map has some deeper meaning – also use separate class. If not, then probably it is better to leave it as pure map to avoid having too many classes.