Plan an object graph refactor disallowing circular references and enforcing aggregate…
- User
Plan an object graph refactor disallowing circular references and enforcing aggregate boundaries.
- Assistant
We are going to design an object graph refactor that disallows circular references and enforces aggregate boundaries. Steps:
- Understand the current object graph (if any) or the domain model we are working with.
- Identify aggregates and their boundaries according to domain-driven design (DDD) principles.
- Ensure that references from one aggregate to another are only by identity (i.e., store the ID of the other aggregate, not a direct object reference).
- Disallow circular references by ensuring that aggregates only reference other aggregates by ID and that within an aggregate, there are no cycles in the object graph (unless necessary and then we must break them by using IDs or weak references?).
- Implement the changes in the codebase.
However, note: the problem does not specify a particular existing codebase, so we will outline a general approach and then provide an example.
Let's assume we have a domain with two aggregates:
OrderandCustomer.Without boundaries, we might have: class Order { Customer customer; // direct reference to another aggregate List items; }
class Customer { List orders; // direct reference to another aggregate String name; }
This creates a circular reference and violates the aggregate boundary because
OrderandCustomerare separate aggregates.We want to change it to:
class Order { private CustomerId customerId; // only store the ID of the customer private List items; // ... methods to get customer details would go through a repository or service }
class Customer { // We do not store a list of Order IDs in the Customer aggregate if we consider that the relationship is from Order to Customer. // But if we need to know the orders of a customer, we might query by customerId. Alternatively, we can store a list of order IDs? // However, note: in DDD, it's common to have a bi-directional relationship only if necessary and then by IDs.
// Option 1: Do not store order IDs in Customer. Then to get orders of a customer, we query the Order repository by customerId. // Option 2: Store a list of order IDs in Customer, but then we must update this list when orders are added/removed. This can be complex. // Typically, we choose the side that is more natural for the domain. Since Order is the one that has a customer, we might only store customerId in Order. // Then, to get orders for a customer, we do: orderRepository.findByCustomerId(customerId) // So we might have: // class Customer { // private CustomerId id; // private String name; // } // But if we need to show a list of order IDs in the customer (for example, in a UI), we might not store them and instead query. // However, if the domain requires that the Customer aggregate must know about its orders (for example, to enforce a business rule that a customer cannot have more than 10 open orders), // then we might store the order IDs in the Customer aggregate. But note: this creates a bidirectional relationship and we must be cautious about consistency. // Since we are enforcing aggregate boundaries, we can store the IDs of the related aggregates but not the actual objects. // Let's assume we decide to store order IDs in Customer because we have a business rule that limits the number of open orders. // Then: // class Customer { // private CustomerId id; // private String name; // private List<OrderId> openOrderIds; // only the IDs of open orders // } // But note: the Order aggregate would then have a reference to Customer by ID, and Customer would have a list of Order IDs. // This is a bidirectional relationship by ID and is acceptable as long as we don't have a cycle in the object graph (because we are only storing IDs, not objects). // However, we must be cautious: if we have a cycle of aggregates referencing each other by ID, that's okay because the actual objects are not loaded at the same time (lazy loading might break this?). // But in terms of the in-memory object graph, if we load a Customer and then for each openOrderId we load the Order, and then each Order has a customerId that points back to the same Customer, then we have a cycle in the object graph. // This cycle is in the loaded objects and might cause issues with serialization (like JSON) and equality. // How to avoid? We can break the cycle by not loading the entire graph at once. But if we do, we might use DTOs that break the cycle. // Alternatively, we can design the aggregates so that the relationship is unidirectional. For example, only Order has customerId, and we don't store orderIds in Customer. // Then when we need to check the open orders for a customer, we query the Order repository. This is often the simpler and more common approach. // Let's go with unidirectional: Order -> Customer (by ID) and no back reference in Customer.}
So, we decide:
Order aggregate: - customerId (CustomerId) - items (list of OrderItem, which are part of the Order aggregate)
Customer aggregate: - id (CustomerId) - name (String)
Then, to get orders for a customer, we use: orderRepository.findByCustomerId(customerId)
This breaks the circular reference and enforces the aggregate boundary.
-
We must also consider that within an aggregate, there might be circular references. For example, an Employee aggregate might have a manager which is also an Employee (same aggregate). That is allowed because it's within the same aggregate. But if we have two different aggregates, we break the cycle by using IDs.
-
Implementation steps for refactoring:
a. Identify all aggregates and their boundaries. b. For each relationship between two different aggregates, replace the object reference with the ID of the target aggregate. c. Remove any bidirectional relationships that are not necessary. If they are necessary, store the IDs on both sides? But note: storing IDs on both sides can lead to consistency issues (we must update both sides). Alternatively, we can store the relationship on one side and query the other way. This is the recommended approach in DDD: choose one side as the owner of the relationship.
d. Update the repository and service layer to handle the ID references. For example, when we need to get the Customer from an Order, we would use the customerId to load the Customer from the CustomerRepository.
e. Update any business logic that previously navigated the object graph directly.
f. Ensure that we do not have cycles in the in-memory object graph when loading aggregates. Since we are only storing IDs for cross-aggregate references, when we load an aggregate we don't automatically load the other aggregates. But if we do load them (e.g., in a service method we load both the Order and the Customer), then we might create a cycle if we also load the orders of the customer? That would be a cycle: Order -> Customer (by loading) -> (if we then load orders of that customer) -> Order (the same or another) -> Customer ... So we must be cautious in our service layer to avoid loading entire graphs that cause cycles.
g. For serialization (like to JSON), we might use DTOs that break the cycle, or we can use annotations to ignore back references.
-
Example code change:
Before:
public class Order { private Customer customer; private List items; }
public class Customer { private List orders; private String name; }
After:
public class Order { private CustomerId customerId; // value object or just String/Long private List items;
// We might have a method to get the customer, but it would require a repository. // Alternatively, we don't put such method in the aggregate and let the service handle it.}
public class Customer { private CustomerId id; private String name; // No orders list }
Then, in a service:
public Order getOrderWithCustomer(OrderId orderId) { Order order = orderRepository.findById(orderId); Customer customer = customerRepository.findById(order.getCustomerId()); // Now we have both, but note: if we then try to get orders of this customer, we might cause a cycle. // So we might only load what we need. }
-
How to handle aggregate roots? Only aggregate roots can be loaded from repositories. So the Order and Customer are aggregate roots.
-
Also, note that the OrderItem is part of the Order aggregate, so it's okay for Order to have a list of OrderItem.
-
If we have a relationship within the same aggregate (like Order and OrderItem) that is bidirectional, that is allowed because they are in the same aggregate. But we must break cycles if they are not necessary.
Example of within aggregate:
class Order { List items; }
class OrderItem { Order order; // this creates a cycle within the aggregate. We might not want that.
We can break it by having OrderItem not reference Order, and then in Order we have the list. But if we need to get the order from an OrderItem, we can pass the order as a parameter when needed.
Alternatively, we can keep it if the domain requires it. But note: within an aggregate, we are allowed to have cycles because the aggregate is a cluster of objects that can be treated as a unit.
However, for serialization and to avoid memory leaks, we might want to break the cycle even within an aggregate? It depends.
But the problem says "disallowing circular references" - does that mean within the entire object graph or only across aggregates?
Typically, in DDD, we break cycles across aggregates but allow within an aggregate? But even within an aggregate, cycles can cause issues.
We are going to interpret the requirement as: no circular references in the entire object graph (including within aggregates) because the requirement says "object graph refactor".
So we must break all cycles.
How to break within an aggregate? We can use weak references? But that's not typical in DDD.
Alternatively, we can design the aggregate so that the relationship is unidirectional. For example, only Order has the list of OrderItem, and OrderItem does not have a reference to Order.
Then, when we need to get the order from an OrderItem, we can pass the order as a parameter to the method that needs it, or we can have a service that knows the relationship.
But note: OrderItem is an entity within the Order aggregate. It is common for OrderItem to have a back reference to Order? Not necessarily.
Let's change:
class Order { private List<OrderItem> items; } class OrderItem { // no reference to Order private String productId; private int quantity; }Then, if we need to know the order of an OrderItem, we can't get it from the OrderItem. But that's okay because the OrderItem is only used within the context of an Order.
However, if we have a use case where we have an OrderItem and we need to know the Order, then we must have a way to get the Order. Since OrderItem is not an aggregate root, we cannot load it by itself. We must load the Order that contains it.
So, we might not need the back reference.
But if we do need it (for example, to get the customer from the order when we have an order item), we can do:
Order order = orderRepository.findOrderByOrderItemId(orderItemId); // but note: orderItemId is not an aggregate root, so we don't have a repository for OrderItem.Alternatively, we can store the orderId in OrderItem? But then we are storing an ID of the same aggregate. That's allowed because it's the same aggregate. However, then we have:
class Order { List<OrderItem> items; } class OrderItem { OrderId orderId; // but note: the OrderId is the same as the Order that contains it? How do we ensure consistency? We must set the orderId in OrderItem when we add it to the Order. And then we have two ways to get the order: from the Order's items (which have orderId) and from the Order itself. This creates a cycle: Order -> OrderItem (by list) and OrderItem -> Order (by orderId). But note: the orderId in OrderItem is the same as the Order that contains it? Yes, but then we are storing redundant information. We can avoid by not having the orderId in OrderItem and only having the bidirectional link? But that's the cycle we are trying to break.So, we decide:
Option 1: Unidirectional from Order to OrderItem. Then we cannot get the order from an order item without having the order. Option 2: Store the orderId in OrderItem and break the bidirectional link by not having a reference to the Order object. Then we have: Order { List<OrderItem> items; // each OrderItem has an orderId, but we don't set it because we already know the order? Actually, we set the orderId in OrderItem to the current order's id. Then, if we have an OrderItem and we want to get the Order, we can use the orderId to load the Order (but note: the OrderItem is part of the Order aggregate, so we should already have the Order?). This is getting complex.Given the requirement to break all circular references, we choose:
- Within an aggregate, we allow unidirectional references from the root to the children, but not the other way. So, Order (root) -> OrderItem (child). OrderItem does not reference Order. Then, if we have an OrderItem and we need the Order, we must have the Order already (because we loaded the Order to get the OrderItem). So we don't need the back reference.But what if we have an OrderItem and we don't have the Order? Then we cannot get the Order because OrderItem is not an aggregate root and we don't have a repository for it.
So, we must design our use cases so that we always have the Order when we are dealing with OrderItem.
This is typical: we load the Order aggregate and then work with its OrderItems.
Therefore, we break the cycle by having only the root hold references to the children.
-
Summary of rules for the refactor:
a. Aggregates are clusters of objects that can be treated as a unit. Only the aggregate root can be loaded from a repository.
b. References from one aggregate to another must be by ID (the ID of the target aggregate root).
c. Within an aggregate, references from the root to the children are allowed (by object reference). References from a child to the root are allowed? We said we break cycles, so we disallow child to root? But then how does a child know its root? It doesn't need to if we design the methods properly.
Example: In the Order aggregate, we have OrderItem. If we need to get the order's customer from an OrderItem, we cannot because OrderItem doesn't have a reference to Order.
So we must design the methods in the Order aggregate to expose what we need without having to go through OrderItem.
For example, if we need to get the customer for an order item, we can have:
Order.getCustomerForOrderItem(OrderItem item) // but that's odd because the Order already has the customer.Alternatively, we can have:
OrderItem.getOrder() // which returns the Order? But that would be a back reference.We are in a dilemma.
Let's reconsider: maybe we allow the child to have a reference to the root within the same aggregate? That would create a cycle in the object graph: Order -> OrderItem (list) and OrderItem -> Order (if we have a field).
But note: the requirement is to disallow circular references. So we must break that.
How about:
OrderItem does not have a reference to Order. Instead, when we need to get the Order from an OrderItem, we pass the Order as a parameter to the method that needs it.Example:
public class Order { public Customer getCustomerForOrderItem(OrderItem item) { return this.customer; } }Then we call: order.getCustomerForOrderItem(someOrderItem)
But then we must have the order instance to call that method. So we are passing the order implicitly.
Alternatively, we can have:
public class OrderItem { // no reference to Order public Customer getCustomer(Order order) { return order.getCustomer(); } }That's awkward.
Given the complexity, maybe we relax the rule for within the same aggregate? Because the aggregate is a cluster and we are going to load it as a whole.
But the requirement says "disallowing circular references", so we must break even within aggregates.
So, we design the aggregate so that the root is the only one that holds references to other objects (within the aggregate) and the children do not hold references to the root or to each other in a way that creates a cycle.
Example:
Order (root) has: - customerId (reference to another aggregate by ID) - List<OrderItem> items // OrderItem does not have a reference back to Order. Then, if we need to get the customer from an OrderItem, we cannot because the OrderItem doesn't have the customerId. But the Order does.So, we must design our domain logic to operate on the root and not on the children in isolation.
This is a constraint we must accept.
-
Conclusion:
We will refactor the code to:
- Ensure that every aggregate has a root that is the only entry point.
- All references from one aggregate to another are by ID (the ID of the target aggregate root).
- Within an aggregate, the root may reference its children (by object reference) but the children must not reference the root or other children in a way that creates a cycle.
However, note: if we have two children that reference each other, that's a cycle. So we must break that too.
Example: within an aggregate, we have A and B. If A has a reference to B and B has a reference to A, that's a cycle. We must break it by making one of them not store the reference, or store an ID? But within the same aggregate, we can break by design.
Since we are loading the entire aggregate at once, we can have a tree structure (no cycles) within the aggregate.
So, the aggregate structure should be a tree (or a directed acyclic graph) with the root at the top.
We can have a child reference multiple other children? That's okay as long as there's no cycle.
Example: Order (root) -> OrderItem1 -> OrderItem2
OrderItem1 and OrderItem2 do not reference each other or the Order.That's a tree.
Therefore, we must review the entire object graph and ensure:
a. Cross-aggregate references are by ID. b. Within an aggregate, the graph is a tree (or at least acyclic) with the root having outgoing references and the children having no outgoing references to the root or to each other in a cycle.
But note: sometimes we need to have a child reference another child (like a parent-child relationship within the same aggregate). Example: a Category aggregate that has a parent category (which is also in the same aggregate). That creates a cycle? Only if the parent also has a reference to the child? Usually, we have:
Category (root) has a tree of categories. Each Category (child) has a parentId (or parent reference) and a list of children. But then we have:
Category (child) -> parent (which is another Category in the same aggregate) and parent -> children (which includes the child). That's a cycle.How to break? We can store the parentId in the child and not store the children list in the parent? Then we have a tree by parentId. But then we cannot traverse from parent to children without a query.
Alternatively, we store the children list in the parent and the parentId in the child. That's bidirectional and creates a cycle.
We must break the cycle. We can choose:
Option 1: Only store the parentId in the child and not store the children list in the parent. Then to get the children of a parent, we query the children by parentId (within the same aggregate). But note: the aggregate is loaded as a whole, so we can have a root that holds a list of all categories? Then we can find the children by filtering by parentId. Option 2: Only store the children list in the parent and not store the parentId in the child. Then we can get the parent of a child by having the parent's ID? We don't have it.So, we store the parentId in the child and the root has the entire list of categories? Then we can build the tree in memory.
Example:
class Category { private CategoryId id; private CategoryId parentId; // null for root private String name; } Then, when we load the Category aggregate (which is a tree of categories), we load all categories with the same root? Actually, the aggregate root might be the entire tree? Or the root category? In DDD, the aggregate root for a tree might be the root node. But then the root node has a list of children? And each child has a parent reference? That would be a cycle.Alternatively, we can have:
class CategoryTree { private Category root; private List<Category> allCategories; // but that's not a tree structure. We want to model a tree.Let's define:
class Category { private CategoryId id; private CategoryId parentId; private String name; } Then, we don't have a cycle because each category points to its parent (by ID) and we don't have a children list. Then, to get the children of a category, we filter the list of categories by parentId. But then the aggregate root is what? We might have a CategoryRoot that is the root of the tree? Or we can have a repository for Category that loads the entire tree? Actually, the aggregate root for a tree might be the root node, but then the root node has children? And the children have parentId? That would be: class Category { private CategoryId id; private CategoryId parentId; // for non-root private String name; private List<Category> children; // only for non-root? No, for root too. Then we have a cycle: parent -> children -> parent. So we break by not having the children list. Then the aggregate root is the root category, and we store all categories in the aggregate? But then how do we get the children? We must have a way to get them. We can have: class Category { private CategoryId id; private CategoryId parentId; private String name; } class CategoryTree { private Category root; private List<Category> categories; // all categories in the tree, including root. Then, to get the children of a category, we do: categories.stream().filter(c -> c.getParentId().equals(currentCategoryId)).collect(...) But note: the CategoryTree is the aggregate root? Then we have a root (which is a Category) and a list of all categories. This is a tree structure without cycles because the Category objects do not have a children list. However, the CategoryTree has a root and a list of categories. The root is in the list? Yes. Then we have: CategoryTree -> root (Category) and CategoryTree -> List<Category> (which includes the root and all others). That's not a cycle because the Category objects do not reference each other. So, the aggregate root is CategoryTree, and it holds a list of all Category objects (which are entities). The Category objects have parentId but no children list. This breaks the cycle.But note: the requirement says "disallowing circular references", and we have:
CategoryTree -> List<Category> -> (each Category has parentId, which is a CategoryId, not a Category object) -> no cycle.So, we are safe.
-
Implementation:
We will:
Step 1: Identify aggregates and their roots.
Step 2: For each aggregate, design the internal structure to be a tree (or at least acyclic) by having the root hold the children (by object reference) and the children only hold IDs (or no reference to parent if we use parentId in the child and then the root holds the entire list?).
But note: if we have a child that needs to reference its parent, we can store the parentId in the child. Then the child does not have a reference to the parent object, only the ID.
Then, the root (which holds all children) can provide a method to get the parent of a child by looking up the parentId in the list? But that would be inefficient.
Alternatively, we can have the root build a map of parentId to children? Then we can get the children quickly.
But note: the root is the aggregate root and it holds the entire state of the aggregate. We can compute the tree structure from the flat list of categories (each with a parentId) and the root category (which has parentId=null).
So, the aggregate root (CategoryTree) would have:
private CategoryId rootId; private List<Category> categories; // all categoriesThen, we can have a method:
public List<Category> getChildren(CategoryId parentId) { return categories.stream().filter(c -> c.getParentId().equals(parentId)).collect(Collectors.toList()); }And the root category is the one with parentId=null.
This way, we don't have cycles.
Step 3: For cross-aggregate references, use IDs.
Step 4: Update the code accordingly.
-
Example:
Let's take a simple example of an e-commerce system with Order and Customer.
Before:
public class Order { private Customer customer; private List items; }
public class Customer { private List orders; private String name; }
public class OrderItem { private Order order; private String productId; private int quantity; }
After:
// Aggregate root: Order public class Order { private OrderId id; private CustomerId customerId; // reference to another aggregate by ID private List items; // OrderItem is part of the Order aggregate
// methods public void addItem(String productId, int quantity) { OrderItem item = new OrderItem(this.id, productId, quantity); // pass the orderId to OrderItem? Or let OrderItem not store orderId? items.add(item); } // We don't have a reference to the Order object in OrderItem? We can store the orderId in OrderItem if we need to know which order an item belongs to when we look at the item alone? // But note: we are not going to look at OrderItem without the Order because it's not an aggregate root. // So we can have: public static class OrderItem { private OrderItemId id; private String productId; private int quantity; // no orderId because we are within the Order aggregate and we don't need it? But if we want to get the order from an OrderItem, we cannot. // However, if we have a use case where we have an OrderItem and we need to know the order, we must have the order already (because we loaded the Order to get the OrderItem). // So we don't store orderId in OrderItem. }}
// But then, if we want to get the order for an OrderItem (when we have the OrderItem and the Order is not loaded), we cannot. But we shouldn't be in that situation because OrderItem is not an aggregate root.
// Alternatively, we can store the orderId in OrderItem for consistency? But then we are storing redundant information (the orderId is already known by the Order that contains it).
// We decide: do not store orderId in OrderItem because we are within the same aggregate and the OrderItem is only used in the context of an Order.
// Then, if we need to get the order from an OrderItem, we must have the Order instance.
// Now, the Customer aggregate:
public class Customer { private CustomerId id; private String name; // no orders list }
// Then, to get the orders for a customer, we do:
List orders = orderRepository.findByCustomerId(customerId);
// This breaks the circular reference and enforces aggregate boundaries.
-
Challenges:
-
We must update all the code that previously navigated from Customer to Order or from OrderItem to Order.
-
We must ensure that we don't accidentally create cycles by loading multiple aggregates and then linking them in memory.
-
We must update the repositories to load aggregates by ID and not by navigating relationships.
-
-
Testing:
We must write tests to ensure that:
a. The object graph of an aggregate does not contain cycles (we can use a cycle detection algorithm in tests?).
b. Cross-aggregate references are by ID.
c. Business logic that previously used direct references now uses IDs and repository lookups.
-
Conclusion:
This refactor is a significant change and must be done carefully, with a good understanding of the domain and the existing code.
We must also consider performance: instead of loading an entire aggregate, we might now need to load multiple aggregates (like Order and then Customer) which might be more expensive.
But this is the trade-off for maintaining aggregate boundaries and avoiding circular references.
-
Note: The above example and explanation are for a typical DDD approach. However, the requirement might be for a different context. Adjust accordingly.
Since the problem does not specify a particular codebase, we have provided a general approach and an example.
Let me know if you have any questions or need further details. I'll outline a comprehensive approach to refactoring an object graph to disallow circular references and enforce aggregate boundaries, based on Domain-Driven Design (DDD) principles.
Core Principles
1. Aggregate Boundaries
- Definition: Aggregates are clusters of domain objects that can be treated as a single unit.
- Rule: Only aggregate roots can be directly referenced from outside the aggregate.
- Rule: All internal references within an aggregate are allowed (including bidirectional).
- Rule: External aggregates are referenced only by their identity (ID), never by object reference.
2. Circular Reference Rules
- Disallowed: Object A → Object B → Object A (anywhere in the graph)
- Allowed: Within a single aggregate (internal object cycles are permitted)
- Allowed: Unidirectional references across aggregates (A→B but not B→A)
- Allowed: Identity-only references across aggregates (A has B's ID, not B object)
Refactoring Strategy
Phase 1: Analysis & Mapping
// 1. Map current object graph Graph<Class<?>> currentGraph = buildDependencyGraph(); Set<Cycle> cycles = detectCycles(currentGraph); Map<Class<?>, AggregateCandidate> aggregateCandidates = identifyPotentialAggregates(); // 2. Identify existing aggregates (if any) Set<Aggregate> existingAggregates = findExistingAggregates(); // 3. Document all cross-aggregate references Map<Class<?>, Set<Class<?>>> crossAggregateRefs = findCrossAggregateReferences();Phase 2: Define Aggregate Boundaries
public class AggregateDefinition { private Class<?> rootEntity; private Set<Class<?>> containedEntities = new HashSet<>(); private Set<Class<?>> allowedExternalReferences = new HashSet<>(); // by ID only public boolean isPartOfAggregate(Class<?> clazz) { return rootEntity.equals(clazz) || containedEntities.contains(clazz); } public boolean canReferenceExternally(Class<?> targetAggregateRoot) { return allowedExternalReferences.contains(targetAggregateRoot); } }Phase 3: Transformation Rules
Rule 1: Replace Object References with IDs
// BEFORE (violates boundary) class Order { private Customer customer; // Direct reference to another aggregate private List<OrderItem> items; } // AFTER class Order { private CustomerId customerId; // Only ID reference private List<OrderItem> items; // Methods that need Customer data: public Customer getCustomer(CustomerRepository repo) { return repo.findById(customerId); } }Rule 2: Bidirectional → Unidirectional
// BEFORE (circular) class Parent { private Child child; } class Child { private Parent parent; // Creates cycle } // OPTION 1: Unidirectional (preferred) class Parent { private Child child; // Child doesn't reference Parent } // OPTION 2: Identity-based back-reference class Child { private ParentId parentId; // Only ID, not object }Rule 3: Aggregate Root as Sole Gateway
// BEFORE (external references to non-root) class OrderService { public void process(OrderItem item) { // OrderItem is internal to Order aggregate // Violation: OrderItem should only be accessed via Order } } // AFTER class OrderService { public void process(OrderId orderId) { Order order = orderRepository.findById(orderId); // Work through Order aggregate root only } }Phase 4: Implementation Patterns
Pattern 1: Repository per Aggregate Root
public interface OrderRepository { Order findById(OrderId id); void save(Order order); // NO methods like: List<Order> findByCustomer(Customer customer) // Instead: List<Order> findByCustomerId(CustomerId customerId) } public interface CustomerRepository { Customer findById(CustomerId id); // No methods returningOrders to prevent loading entire graph }Pattern 2: Domain Services for Cross-Aggregate Operations
public class OrderPlacementService { private final OrderRepository orderRepo; private final CustomerRepository customerRepo; private final InventoryService inventoryService; public Order placeOrder(PlaceOrderCommand cmd) { // 1. Validate customer exists (by ID only) CustomerId customerId = cmd.getCustomerId(); customerRepo.findById(customerId); // Throws if not found // 2. Create order aggregate Order order = new Order(customerId, cmd.getItems()); // 3. Check inventory (via service, not direct reference) inventoryService.reserveItems(order.getItems()); orderRepo.save(order); return order; } }Pattern 3: Specification Pattern for Cross-Aggregate Queries
public class CustomerOrderSpecification implements Specification<Order> { private final CustomerId customerId; @Override public boolean isSatisfiedBy(Order order) { return order.getCustomerId().equals(customerId); } // Usage: List<Order> orders = orderRepository.findBySpecification( new CustomerOrderSpecification(customerId) ); }Phase 5: Validation & Testing
Static Analysis Rules
// Custom annotation processor or checker framework rules: @ViolatesAggregateBoundary public class BadService { public void badMethod(InternalEntity entity) { // Forbidden // External code shouldn't depend on internal entities } } @AggregateRoot public class Order { // Only this class can be referenced externally }Runtime Validation
public class AggregateBoundaryValidator { public static void validateGraph(Object root) { Set<Object> visited = new HashSet<>(); validateRecursive(root, visited, new HashSet<>()); } private static void validateRecursive( Object obj, Set<Object> visited, Set<Object> currentPath ) { if (currentPath.contains(obj)) { throw new AggregateCycleException("Cycle detected in object graph"); } // Check all fields for (Field field : obj.getClass().getDeclaredFields()) { field.setAccessible(true); Object value = field.get(obj); if (value != null && !isPrimitiveOrValueType(value.getClass())) { // Check if external aggregate reference uses ID instead of object if (isExternalAggregateReference(field) && !isIdType(field.getType())) { throw new BoundaryViolationException( "External aggregate must be referenced by ID only" ); } validateRecursive(value, visited, new HashSet<>(currentPath) {{ add(obj); }}); } } } }Phase 6: Migration Strategy
- Step 1: Identify all aggregates and their boundaries
- Step 2: Create new ID-based reference fields alongside existing ones
- Step 3: Update repositories to return aggregates with ID references only
- Step 4: Gradually migrate services to use ID-based lookups
- Step 5: Remove old object references
- Step 6: Add validation to prevent regression
Example: E-commerce Refactor
// AGGREGATE 1: Order (Root: Order) public class Order { private OrderId id; private CustomerId customerId; // ID reference only private OrderStatus status; private List<OrderItem> items; // Internal to aggregate public void addItem(ProductId productId, int quantity) { items.add(new OrderItem(productId, quantity)); } public Customer getCustomer(CustomerRepository repo) { return repo.findById(customerId); } } // AGGREGATE 2: Customer (Root: Customer) public class Customer { private CustomerId id; private String name; private Email email; // NO reference to orders } // AGGREGATE 3: Product (Root: Product) public class Product { private ProductId id; private String name; private Money price; private InventoryId inventoryId; // Reference to another aggregate by ID } // SERVICE (orchestration across aggregates) public class OrderProcessingService { public Confirmation placeOrder(PlaceOrderRequest request) { // 1. Validate all IDs exist customerRepo.findById(request.getCustomerId()); productRepo.findByIds(request.getProductIds()); // 2. Create order aggregate Order order = new Order(request.getCustomerId()); request.getItems().forEach(item -> order.addItem(item.getProductId(), item.getQuantity()) ); // 3. Check inventory via service (not direct reference) inventoryService.checkAvailability(order.getItems()); orderRepo.save(order); return new Confirmation(order.getId()); } }Key Benefits
- Clear boundaries: Each aggregate is independently loadable/saveable
- No cycles: Object graph is a directed acyclic graph (DAG)
- Loose coupling: Aggregates don't know about each other's internal structure
- Scalability: Easier to distribute aggregates across services/nodes
- Testability: Each aggregate can be tested in isolation
Common Pitfalls to Avoid
- Leaky abstractions: Don't expose internal entities outside the aggregate
- God aggregates: Don't make aggregates too large (typical: 1-10 entities)
- Overhead: Too many ID lookups can impact performance (use caching where appropriate)
- Eventual consistency: Cross-aggregate operations need compensating transactions
- Query mismatch: Complex queries may require separate read models (CQRS)
Tools & Techniques
- Static analysis: ArchUnit, SonarQube custom rules
- Runtime checks: Aspect-oriented programming for boundary validation
- Migrations: Database refactoring tools (Liquibase/Flyway) for ID-based relationships
- Documentation: Architecture decision records (ADRs) for aggregate boundaries
Would you like me to elaborate on any specific aspect or provide code examples for your particular domain?
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.