- Using Aggregates in the Scrum Core Domain
- Rule: Model True Invariants in Consistency Boundaries
- Rule: Design Small Aggregates
- Rule: Reference Other Aggregates by Identity
- Rule: Use Eventual Consistency Outside the Boundary
- Reasons to Break the Rules
- Gaining Insight through Discovery
- Implementation
- Wrap-Up
Implementation
The more prominent factors summarized and highlighted here can make implementations more robust but should be investigated more thoroughly in Entities (5), Value Objects (6), Domain Events (8), Modules (9), Factories (11), and Repositories (12). Use this amalgamation as a point of reference.
Create a Root Entity with Unique Identity
Model one Entity as the Aggregate Root. Examples of Root Entities in the preceding modeling efforts are Product, BacklogItem, Release, and Sprint. Depending on the decision made to split Task from BacklogItem, Task may also be a Root.
The refined Product model finally led to the declaration of the following Root Entity:
public class Product extends ConcurrencySafeEntity { private Set<ProductBacklogItem> backlogItems; private String description; private String name; private ProductDiscussion productDiscussion; private ProductId productId; private TenantId tenantId; ... }
Class ConcurrencySafeEntity is a Layer Supertype [Fowler, P of EAA] used to manage surrogate identity and optimistic concurrency versioning, as explained in Entities (5).
A Set of ProductBacklogItem instances not previously discussed has been, perhaps mysteriously, added to the Root. This is for a special purpose. It’s not the same as the BacklogItem collection that was formerly composed here. It is for the purpose of maintaining a separate ordering of backlog items.
Each Root must be designed with a globally unique identity. The Product has been modeled with a Value type named ProductId. That type is the domain-specific identity, and it is different from the surrogate identity provided by ConcurrencySafeEntity. How a model-based identity is designed, allocated, and maintained is further explained in Entities (5). The implementation of ProductRepository has nextIdentity() generate ProductId as a UUID:
public class HibernateProductRepository implements ProductRepository { ... public ProductId nextIdentity() { return new ProductId(java.util.UUID.randomUUID()↵ .toString().toUpperCase()); } ... }
Using nextIdentity(), a client Application Service can instantiate a Product with its globally unique identity:
public class ProductService ... { ... @Transactional public String newProduct( String aTenantId, aProductName, aProductDescription) { Product product = new Product( new TenantId(aTenantId), this.productRepository.nextIdentity(), "My Product", "This is the description of my product.", new ProductDiscussion( new DiscussionDescriptor( DiscussionDescriptor.UNDEFINED_ID), DiscussionAvailability.NOT_REQUESTED)); this.productRepository.add(product); return product.productId().id(); } ... }
The Application Service uses ProductRepository to both generate an identity and then persist the new Product instance. It returns the plain String representation of the new ProductId.
Favor Value Object Parts
Choose to model a contained Aggregate part as a Value Object rather than an Entity whenever possible. A contained part that can be completely replaced, if its replacement does not cause significant overhead in the model or infrastructure, is the best candidate.
Our current Product model is designed with two simple attributes and three Value-typed properties. Both description and name are String attributes that can be completely replaced. The productId and tenantId Values are maintained as stable identities; that is, they are never changed after construction. They support reference by identity rather than direct to object. In fact, the referenced Tenant Aggregate is not even in the same Bounded Context and thus should be referenced only by identity. The productDiscussion is an eventually consistent Value-typed property. When the Product is first instantiated, the discussion may be requested but will not exist until sometime later. It must be created in the Collaboration Context. Once the creation has been completed in the other Bounded Context, the identity and status are set on the Product.
There are good reasons why ProductBacklogItem is modeled as an Entity rather than a Value. As discussed in Value Objects (6), since the backing database is used via Hibernate, it must model collections of Values as database entities. Reordering any one of the elements could cause a significant number, even all, of the ProductBacklogItem instances to be deleted and replaced. That would tend to cause significant overhead in the infrastructure. As an Entity, it allows the ordering attribute to be changed across any and all collection elements as often as a product owner requires. However, if we were to switch from using Hibernate with MySQL to a key-value store, we could easily change ProductBacklogItem to be a Value type instead. When using a key-value or document store, Aggregate instances are typically serialized as one value representation for storage.
Using Law of Demeter and Tell, Don’t Ask
Both Law of Demeter [Appleton, LoD] and Tell, Don’t Ask [PragProg, TDA] are design principles that can be used when implementing Aggregates, both of which stress information hiding. Consider the high-level guiding principles to see how we can benefit:
- Law of Demeter: This guideline emphasizes the principle of least knowledge. Think of a client object and another object the client object uses to execute some system behavior; refer to the second object as a server. When the client object uses the server object, it should know as little as possible about the server’s structure. The server’s attributes and properties–its shape–should remain completely unknown to the client. The client can ask the server to perform a command that is declared on its surface interface. However, the client must not reach into the server, ask the server for some inner part, and then execute a command on the part. If the client needs a service that is rendered by the server’s inner parts, the client must not be given access to the inner parts to request that behavior. The server should instead provide only a surface interface and, when invoked, delegate to the appropriate inner parts to fulfill its interface.
Here’s a basic summary of the Law of Demeter: Any given method on any object may invoke methods only on the following: (1) itself, (2) any parameters passed to it, (3) any object it instantiates, (4) self-contained part objects that it can directly access.
- Tell, Don’t Ask: This guideline simply asserts that objects should be told what to do. The “Don’t Ask” part of the guideline applies to the client as follows: A client object should not ask a server object for its contained parts, then make a decision based on the state it got, and then make the server object do something. Instead, the client should “Tell” a server what to do, using a command on the server’s public interface. This guideline has very similar motivations as Law of Demeter, but Tell, Don’t Ask may be easier to apply broadly.
Given these guidelines, let’s see how we apply the two design principles to Product:
public class Product extends ConcurrencySafeEntity { ... public void reorderFrom(BacklogItemId anId, int anOrdering) { for (ProductBacklogItem pbi : this.backlogItems()) { pbi.reorderFrom(anId, anOrdering); } } public Set<ProductBacklogItem> backlogItems() { return this.backlogItems; } ... }
The Product requires clients to use its method reorderFrom() to execute a state-modifying command in its contained backlogItems. That is a good application of the guidelines. Yet, method backlogItems() is also public. Does this break the principles we are trying to follow by exposing ProductBacklogItem instances to clients? It does expose the collection, but clients may use those instances only to query information from them. Because of the limited public interface of ProductBacklogItem, clients cannot determine the shape of Product by deep navigation. Clients are given least knowledge. As far as clients are concerned, the returned collection instances may have been created only for the single operation and may represent no definite state of Product. Clients may never execute state-altering commands on the instances of ProductBacklogItem, as its implementation indicates:
public class ProductBacklogItem extends ConcurrencySafeEntity { ... protected void reorderFrom(BacklogItemId anId, int anOrdering) { if (this.backlogItemId().equals(anId)) { this.setOrdering(anOrdering); } else if (this.ordering() >= anOrdering) { this.setOrdering(this.ordering() + 1); } } ... }
Its only state-modifying behavior is declared as a hidden, protected method. Thus, clients can’t see or reach this command. For all practical purposes, only Product can see it and execute the command. Clients may use only the Product public reorderFrom() command method. When invoked, the Product delegates to all its internal ProductBacklogItem instances to perform the inner modifications.
The implementation of Product limits knowledge about itself, is more easily tested, and is more maintainable, due to the application of these simple design principles.
You will need to weigh the competing forces between use of Law of Demeter and Tell, Don’t Ask. Certainly the Law of Demeter approach is much more restrictive, disallowing all navigation into Aggregate parts beyond the Root. On the other hand, the use of Tell, Don’t Ask allows for navigation beyond the Root but does stipulate that modification of the Aggregate state belongs to the Aggregate, not the client. You may thus find Tell, Don’t Ask to be a more broadly applicable approach to Aggregate implementation.
Optimistic Concurrency
Next, we need to consider where to place the optimistic concurrency version attribute. When we contemplate the definition of Aggregate, it could seem safest to version only the Root Entity. The Root’s version would be incremented every time a state-altering command is executed anywhere inside the Aggregate boundary, no matter how deep. Using the running example, Product would have a version attribute, and when any of its describeAs(), initiateDiscussion(), rename(), or reorderFrom() command methods are executed, the version would always be incremented. This would prevent any other client from simultaneously modifying any attributes or properties anywhere inside the same Product. Depending on the given Aggregate design, this may be difficult to manage, and even unnecessary.
Assuming we are using Hibernate, when the Product name or description is modified, or its productDiscussion is attached, the version is automatically incremented. That’s a given, because those elements are directly held by the Root Entity. However, how do we see to it that the Product version is incremented when any of its backlogItems are reordered? Actually, we can’t, or at least not automatically. Hibernate will not consider a modification to a ProductBacklogItem part instance as a modification to the Product itself. To solve this, perhaps we could just change the Product method reorderFrom(), dirtying some flag or just incrementing the version on our own:
public class Product extends ConcurrencySafeEntity { ... public void reorderFrom(BacklogItemId anId, int anOrdering) { for (ProductBacklogItem pbi : this.backlogItems()) { pbi.reorderFrom(anId, anOrdering); } this.version(this.version() + 1); } ... }
One problem is that this code always dirties the Product, even when a reordering command actually has no effect. Further, this code leaks infrastructural concerns into the model, which is a less desirable domain modeling choice if it can be avoided. What else can be done?
Cowboy Logic
AJ: “I’m thinkin’ that marriage is a sort of optimistic concurrency. When a man gets married, he is optimistic that the gal will never change. And at the same time, she’s optimistic that he will.”
Actually in the case of the Product and its ProductBacklogItem instances, it’s possible that we don’t need to modify the Root’s version when any backlogItems are modified. Since the collected instances are themselves Entities, they can carry their own optimistic concurrency version. If two clients reorder any of the same ProductBacklogItem instances, the last client to commit changes will fail. Admittedly, overlapping reordering would rarely if ever happen, because it’s usually only the product owner who reorders the product backlog items.
Versioning all Entity parts doesn’t work in every case. Sometimes the only way to protect an invariant is to modify the Root version. This can be accomplished more easily if we can modify a legitimate property on the Root. In this case, the Root’s property would always be modified in response to a deeper part modification, which in turn causes Hibernate to increment the Root’s version. Recall that this approach was described previously to model the status change on BacklogItem when all of its Task instances have been transitioned to zero hours remaining.
However, that approach may not be possible in all cases. If not, we may be tempted to resort to using hooks provided by the persistence mechanism to manually dirty the Root when Hibernate indicates a part has been modified. This becomes problematic. It can usually be made to work only by maintaining bidirectional associations between child parts and the parent Root. The bidirectional associations allow navigation from a child back to the Root when Hibernate sends a life cycle event to a specialized listener. Not to be forgotten, though, is that [Evans] generally discourages bidirectional associations in most cases. This is especially so if they must be maintained only to deal with optimistic concurrency, which is an infrastructural concern.
Although we don’t want infrastructural concerns to drive modeling decisions, we may be motivated to travel a less painful route. When modifying the Root becomes very difficult and costly, it could be a strong indication that we need to break down our Aggregates to just a Root Entity, containing only simple attributes and Value-typed properties. When our Aggregates consist of only a Root Entity, the Root is always modified when any part is modified.
Finally, it must be acknowledged that the preceding scenarios are not a problem when an entire Aggregate is persisted as one value and the value itself prevents concurrency conflict. This approach can be leveraged when using MongoDB, Riak, Oracle’s Coherence distributed grid, or VMware’s GemFire. For example, when an Aggregate Root implements the Coherence Versionable interface and its Repository uses the VersionedPut entry processor, the Root will always be the single object used for concurrency conflict detection. Other key-value stores may provide similar conveniences.
Avoid Dependency Injection
Dependency injection of a Repository or Domain Service into an Aggregate should generally be viewed as harmful. The motivation may be to look up a dependent object instance from inside the Aggregate. The dependent object could be another Aggregate, or a number of them. As stated earlier under “Rule: Reference Other Aggregates by Identity,” preferably dependent objects are looked up before an Aggregate command method is invoked, and passed in to it. The use of Disconnected Domain Model is generally a less favorable approach.
Additionally, in a very high-traffic, high-volume, high-performance domain, with heavily taxed memory and garbage collection cycles, think of the potential overhead of injecting Repositories and Domain Service instances into Aggregates. How many extra object references would that require? Some may contend that it’s not enough to tax their operational environment, but theirs is probably not the kind of domain being described here. Still, take great care not to add unnecessary overhead that could be easily avoided by using other design principles, such as looking up dependencies before an Aggregate command method is invoked, and passing them in to it.
This is only meant to warn against injecting Repositories and Domain Services into Aggregate instances. Of course, dependency injection is quite suitable for many other design situations. For example, it could be quite useful to inject Repository and Domain Service references into Application Services.