AboElzooz
AboElzooz

Reputation: 319

Object vs Object_id injection in ddd

My question is simple what would be the best to inject the object itself or the object identifier in a ddd environment ?

simple example to clarify the question

Option 1 :

class Car{
   public function addWheel(Wheel $wheel){}
}

Option 2 :

class Car{
   public function addWheel(WheelId $wheel_id){}
}

which option is better ? because every time i decide to use wheel_id i feel that im going PI that its a reference or an embed and in DDD it should be about object interaction any help ?

Upvotes: 0

Views: 137

Answers (2)

Rafał Łużyński
Rafał Łużyński

Reputation: 7312

It's not a simple question. If look into the red book, Vaughn Vernon encourages us to reference aggregates by ids, but only aggregates! If wheel is an entity then you have to pass it as object.

The most difficult part here is to separate aggregates from entites, to do that you have to know what invariants you got in your aggregate.

Here are few reasons why should reference aggregates by ids:

  • when you have to reconstitute aggregate, you also have to load all referenced aggregates, and if object graph is large, then every load of Your aggregate can be very slow. You can overcome this by using lazy loading, but with that you get another problems, which I won't cover here.

  • when you store aggregate, you have to also check if referenced aggregates weren't changed, so you have to store them also, or just store every referenced aggregate by default, which is really performance unwise.

  • by storing few aggregates at once, you can have concurrency problems because of collaborative nature of Your domain. That way app can become even unusable

However, sometimes it's hard to reference all aggregates by ids, it depends on Your domain.

Upvotes: 2

xJoshWalker
xJoshWalker

Reputation: 457

My suggestion would be to pass in the actual Wheel object. Reason being that in the future if you want the addWheel function to check certain attributes of the wheel before adding it to the Car, you will want the wheel to be available to do so. In addition, this would allow you to immediately make use of the Wheel object in your Car class. If you just pass the ID in, then you will have to look it up in the database (making the assumption that ID is for the database) before you can interact with it in the Car class. The ID itself is irrelevant to your Car class, as it is just for persistence of the wheel.

Upvotes: 2

Related Questions