I’m approaching DDD and I’m in trouble with a (very common) scenario where a hierarchy of objects is involved.
Let’s imagine modeling a Software Product made of many Modules bundled together:
Case 1: Using Inheritance
// The 'Product' entity
class Product {
String version; // Identity
Set<Module> modules; // Entities
Date releasedOn; // VO
Author releasedBy; // VO
...
...
}
// The 'Module' Entity
class Module {
ModuleVersion version; // Identity
String name;
ModuleMetadata metadata; // VO
...
}
At the first moment, I identified the “Product” class as an Entity because, in my context, it has an identity (the version).
But the “Product” class is always an aggregation of other objects because it is the parent in a hierarchy tree.
- Is it correct to say that, under some circumstances, an entity also acts as an Aggregate?
- If yes, is it correct to say that, in this case, the entity that acts as Aggregate is the Aggregate root itself?
Another way of modeling the scenario would be the implementation of the “ProductAggregate” to “physically” model the Aggregate, but honestly I can’t see which benefit it can bring to:
// The 'Product' aggregate.
// Which benefit of introducing this wrapper?
class ProductAggregate {
Product product;
}
// The 'Product' entity
class Product {
String version; // Identity
Set<Module> modules; // Entities
Date releasedOn; // VO
Author releasedBy; // VO
...
}
...
Case 2: Using Composition over Inheritance
The “Product” hierarchy is built using composition in place of aggregation:
// The 'Product' aggregate
class ProductAggregate {
Product product;
Set<Module> modules;
...
}
// The 'Product' entity (without modules)
class Product {
String version; // Identity
Date releasedOn; // VO
Author releasedBy; // VO
...
}
In such cases, the “ProductAggregate” class makes sense and the overall model seems to better adhere to the DDD principles. Anyway to my way of thinking about the real world, using composition (Case 2) is less natural than using aggregation (Case 1).
Any suggestion on which modeling strategy is better to use?
Thank you