R – DDD: subclasses & root entities

aggregatedomain-driven-designentityorm

Let's say I have the typical entity Car

class Car : Entity
{
    public double MaxSpeed { get; set; }
    public Color Color { get; set; }
    /* ... */
}

This entity, in my domain model, would be the root entity of an Aggregate.

Now let's say I specialize cars. I create a Ferrari, and the happy owners of Ferraris like to call them by a nickname:

class Ferrari : Car
{
    public string Nickname { get; set; }
}

Let's say I have another entity, the Company entity. It would be the root entity of another Aggregate. There are many people working on a company, represented by the entity Person. Persons may have cars. But the President of a company is usually very rich and this kind of people, they have Ferraris:

class President : Person
{
    public Ferrari Ferrari { get; set; }
}

In this situation, I have the entity President, who is inside the Company Aggregate, that is holding a reference to a Ferrari, an specialization of the root entity of another aggregate.

Is this correct in view of DDD? Can/should I consider the specialization of root entities themselves as root entities of the same aggregate? I mean, in the domain I described, is the entity Ferrari also the root entity of the Car Aggregate (since Ferrari is also a Car)?


Now let's say I have to persist this model to a Database. I think that my question does not depend on the OR/M framework I will use.

How should I build the table holding Cars? Should I build a single table Cars, with a "CarType" column (possible values: "Car", "Ferrari"), and a nullable Nickname column?

Or should I build a table for Cars and a table for Ferraris, the latter one having its PK a FK of Cars?

Thanks!

Best Answer

You shouldn't use inheritance to model your domain because you will soon run into trouble once model starts to get complex.

President is simply a role of the person and person can have multiple roles. Maybe president got just one role but that's simply accidental by choosing wrong example.

Ferrari shouldn't be inherited from car either. It's not obvious on Ferrari example, because they only do one type of cars but consider company making many types like vans, sedans, hatchbacks, trucks and so on. You will probably want to make classes for every type that will inherit from car class. And then what... are you going to make five Toyota classes that will inherit from each type? Such as...

Car -> Sedan -> ToyotaSedan
Car -> Truck -> ToyotaTruck
Car -> Hatchback -> ToyotaHatchback

That would be ridiculous.

Disclaimer: I know nothing about about cars. However...

Don't use inheritance to model your domain. Ever.

Try it without inheritance and it will also became obvious how to persist your domain.

Related Topic