Why might timing matter? Consider a scenario where the client subscribes to outgoing Domain Events. An Event occurs when a newProductinstantiation completes. The client saves the published Event to anEvent Store (8). Eventually those stored Events are published as notifications that reach subscribers outside the Bounded Context. Using the approach of
Figure 5.3, the Domain Event is received before the client has the opportunity to add the newProductto theProductRepository. Thus, the Domain Event would not contain the valid identity of the newProduct. For the Domain Event to be correctly initialized, the identity generation must be completed early.
Figure 5.4demonstrates that approach. The client queries for the next identity from theProductRepository, passing it to theProductconstructor.
There is another problem that can occur when identity generation is delayed until the Entity is persisted. It occurs when two or more new Entities must be added to ajava.util.Set, but their identity has not yet been assigned, making them equal to the other new ones (for example,null, or0, or-1). If the Entity’sequals()method compares identities, those newly added to theSetwill appear to be the same object. Only the first object added will be contained, and all others will be excluded. This causes a dubious bug whose root cause is at first difficult to understand and fix.