Anemic Domain Model Brings a False Sense of Code Reuse

Say there's an instance where a client bypasses UpdateOrderAmountService and instead fetches, updates, and persists directly to OrderRepository. Then, all the extra business logic that the UpdateOrderAmountService service might have won't be executed. This could lead to the order being stored in an inconsistent state. As such, invariants should be correctly guarded, and the best way to do this is to let the true Domain Model handle it. In the case of this example, the Order Entity would be the best place to ensure this:

class Order 
{
// ...

public function changeAmount($amount)
{
$this->amount = $amount;
$this->setUpdatedAt(new DateTimeImmutable());
}
}

Note that by pushing this action down into the Entity and naming it in terms of the Ubiquitous Language, the system achieves great code reuse. Anyone who now wishes to change the amount of the order has to invoke the Order::changeAmount method directly.

This leads to far richer classes, where behavior is the goal for code reuse. This is commonly referred to as a Rich Domain Model.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset