Equivalent of Aggregate where there is no Entity - domain-driven-design

I have several aggregates: Deposit, Withdraw etc. Now there is a VO called Ledger, which has other related VOs as well. Ledger marks the transaction for both the Deposit and Withdraw, which ever takes place. In this case, it seems similar to making a separate aggregate(creating a folder and placing Ledger and related types into it). But DDD won't allow me that, because Aggregate roots can only be Entities.
What can be the possible solution for it? How can I categorize and place Ledger and related VOs while staying in the boundaries of DDD?
UPDATE:
The ledger is like a record, a transaction for each operation performed. For example, when a deposit has been made, a trade has occurred etc. So it has no state, and will be just saved once and never modified again. It is persisted for record keeping purposes.
Deposit and Withdraw both have states and a lifetime, their status will change from Pending to Confirmation, or from Pending to Cancelled. So they cannot be services.
Please let me know if more information is required.
Thanks in advance.

From your update, it sounds as though you might have a slight terminology issue and a missing entity.
You might need to rename your Ledger value object to LedgerRecord or LedgerEntry.
Your missing entity might then be a Ledger (a ledger is like a book, a container of records or entries). This would have a collection of LedgerRecords.
So you would then maybe call Ledger.MakeEntry(text) or maybe call LedgerService.GetLedgerSectionByDateRange(from, to), which would return a Ledger populated with LedgerRecords from that date range, etc.

First, think of the rest of VOs that are part of the Ledger. Is there any hidden identity that you haven't considered before among these VOs? In that case, that would be the (root) Entity and you would have your Aggregate.
If that's not the case, you could consider whether the Ledger is a VO that is part of an Aggregate in which the root entity is Operation, where Operation is an Entity with unique identity and Withdraw and Deposit would be specializations of it.

Related

DDD Aggregates vs Entities

What to do with an object that has two dependencies:
Let's say we have three objects: client, company and a contract.
Contract needs a client and a company to exist.
Naturally, business wise, the contract belongs more to the client than it does to the company, however the companies provides the contract to the client.
For now, I have all three as a separate aggregate root. Because you should be able to quickly query the existing contracts for a specific company as well. If contract would be an entity under the client aggregate root, I'd need to query all the clients which have a contract of X company and then return a flattened list of those contracts. Which seemed a bit odd?
Secondly, contract itself has a lot of entities, with more entities below them.
To explain the hierarchy in a simple way:
Contract aggregates contains a list of entity A, entity A has multiple items of entity B and entity B has multiple items of entity C. So it's a deep structure, which all have to be exposed through the aggregate above it.
If I'd put the contract aggregate root as an entity below client, my client aggregate needs to carry all those extra methods for what's below contract as well. And soon I'll end up with almost everything under the same aggregate.
So my question is: what questions can I ask myself to answer this kind of issue? There's probably no right or wrong, but there should be some guidelines on how to deal with an issue like this?
Thanks!
what questions can I ask myself to answer this kind of issue?
Here is how Eric Evans defined AGGREGATE
An aggregate is a cluster of associated objects that we treat as a unit for the purpose of data changes.
"Change" is the important idea here; in designing our aggregate boundaries, we don't particularly care about data that appears in the same report (read-only view), we care instead about what data needs be to considered when making changes.
See also Mauro Servienti: All our aggregates are wrong.

DDD Modify one aggregate per transaction with invariants in both aggregates

Suppose I have an aggregate root Tenant and an aggregate root Organization. Multiples Organizations can be linked to a single Tenant. Tenant only has the Id of the Organizations in it's aggregate.
Suppose I have the following invariant in the Organization aggregate: Organization can only have one subscription for a specific product type.
Suppose I have the following invariant in the Tenant aggregate: only one subscription for a product type must exists across all Organizations related to a Tenant.
How can we enforce those invariants using the one aggregate per transaction rule?
When adding a subscription to an Organization, we can easily validate the first invariant, and fire a domain event to update (eventual consistency) the Tenant, but what happens if the invariant is violated in the Tenant aggregate?
Does it imply to fire another domain event to rollback what happens in the Organization aggregate? Seems tricky in the case a response had been sent to a UI after the first aggregate had been modified successfully.
Or is the real approach here is to use a domain service to validate the invariants of both aggregates before initiating the update? If so, do we place the invariants/rules inside the domain service directly or do we place kind of boolean validation methods on aggregates to keep the logic there?
UPDATE
What if the UI must prevent the user from saving in the UI if one invariants is violated? In this case we are not even trying to update an aggregate.
One thing you might want to consider is the possibility of a missing concept in your domain. You might want to explore the possibility of your scenario having something as a Subscription Plan concept, which by itself is an aggregate and enforces all of these rules you're currently trying to put inside the Tenant/Organization aggregates.
When facing such scenarios I tend to think to myself "what would an organization do if there was no system at all facilitating this operation". In your case, if there were multiple people from the same tenant, each responsible for an organization... how would they synchronize their subscriptions to comply with the invariants?
In such an exercise, you will probably reach some of the scenarios already explored:
Have a gathering event (such as a conference call) to make sure no redundant subscriptions are being made: that's the Domain Service path.
Each make their own subscriptions and they notify each other, eventually charging back redundant ones: that's the Event + Rollback path.
They might compromise and keep a shared ledger where they can check how subscriptions are going corporation wide and the ledger is the authority in such decisions: that's the missing aggregate path.
You will probably reach other options if you stress the issue enough.
How can we enforce those invariants using the one aggregate per transaction rule?
There are a few different answers.
One is to abandon the "rule" - limiting yourself to one aggregate per transaction isn't important. What really matters is that all of the objects in the unit of work are stored together, so that the transaction is an all or nothing event.
BEGIN TRANSACTION
UPDATE ORGANIZATION
UPDATE TENANT
COMMIT
A challenge in this design is that the aggregates no longer describe atomic units of storage - the fact that this organization and this tenant need to be stored in the same shard is implicit, rather than explicit.
Another is to redesign your aggregates - boundaries are hard, and its often the case that our first choice of boundaries are wrong. Udi Dahan, in his talk Finding Service Boundaries, observed that (as an example) the domain behaviors associated with a book title usually have little or nothing to do with the book price; they are two separate things that have a relation to a common thing, but they have no rules in common. So they could be treated as part of separate aggregates.
So you can redesign your Organization/Tenant boundaries to more correctly capture the relations between them. Thus, all of the relations that we need to correctly evaluate this rule are in a single aggregate, and therefore necessarily stored together.
The third possibility is to accept that these two aggregates are independent of each other, and the "invariant" is more like a guideline than an actual rule. The two aggregates act like participants in a protocol, and we design into the protocol not only the happy path, but also the failure modes.
The simple forms of these protocols, where we have reversible actions to unwind from a problem, are called sagas. Caitie McCaffrey gave a well received talk on this in 2015, or you could read Clemens Vasters or Bernd Rücker; Garcia-Molina and Salem introduced the term in their study of long lived transactions.
Process Managers are another common term for this idea of a coordinated protocol, where you might have a more complicated graph of states than commit/rollback.
The first idea that came to my mind is to have a property of the organization called "tenantHasSubscription" that property can be updated with domain events. Once you have this property you can enforce the invariant in the organization aggregate.
If you want to be 100% sure that the invariant is never violated, all the commands SubscribeToProduct(TenantId, OrganizationId) have to be managed by the same aggregate (maybe the Tenant), that has internally all the values to check the invariant.
Otherwise to do your operation you will always have to query for an "external" value (from the aggregate point of view), this will introduce "latency" in the operation that open a window for inconsistency.
If you query a db to have values, can it happen that when the result is on the wire, somebody else is updating it, because the db doesn't wait you consumed your read to allow others to modify it, so your aggregate will use stale data to check invariants.
Obviously this is an extremism, this doesn't mean that it is for sure dangerous, but you have to calculate the probability of a failure to happen, how can you be warned when it happen, and how to solve it (automatically by the program, or maybe a manual intervention, depending on the situation).

DDD: do I really need to load all objects in an aggregate? (Performance concerns)

In DDD, a repository loads an entire aggregate - we either load all of it or none of it. This also means that should avoid lazy loading.
My concern is performance-wise. What if this results in loading into memory thousands of objects? For example, an aggregate for Customer comes back with ten thousand Orders.
In this sort of cases, could it mean that I need to redesign and re-think my aggregates? Does DDD offer suggestions regarding this issue?
Take a look at this Effective Aggregate Design series of three articles from Vernon. I found them quite useful to understand when and how you can design smaller aggregates rather than a large-cluster aggregate.
EDIT
I would like to give a couple of examples to improve my previous answer, feel free to share your thoughts about them.
First, a quick definition about an Aggregate (took from Patterns, Principles and Practices of Domain Driven Design book by Scott Millet)
Entities and Value Objects collaborate to form complex relationships that meet invariants within the domain model. When dealing with large interconnected associations of objects, it is often difficult to ensure consistency and concurrency when performing actions against domain objects. Domain-Driven Design has the Aggregate pattern to ensure consistency and to define transactional concurrency boundaries for object graphs. Large models are split by invariants and grouped into aggregates of entities and value objects that are treated as conceptual whole.
Let's go with an example to see the definition in practice.
Simple Example
The first example shows how defining an Aggregate Root helps to ensure consistency when performing actions against domain objects.
Given the next business rule:
Winning auction bids must always be placed before the auction ends. If a winning bid is placed after an auction ends, the domain is in an invalid state because an invariant has been broken and the model has failed to correctly apply domain rules.
Here there is an aggregate consisting of Auction and Bids where the Auction is the Aggregate Root.
If we say that Bid is also a separated Aggregate Root you would have have a BidsRepository, and you could easily do:
var newBid = new Bid(money);
BidsRepository->save(auctionId, newBid);
And you were saving a Bid without passing the defined business rule. However, having the Auction as the only Aggregate Root you are enforcing your design because you need to do something like:
var newBid = new Bid(money);
auction.placeBid(newBid);
auctionRepository.save(auction);
Therefore, you can check your invariant within the method placeBid and nobody can skip it if they want to place a new Bid.
Here it is pretty clear that the state of a Bid depends on the state of an Auction.
Complex Example
Back to your example of Orders being associated to a Customer, looks like there are not invariants that make us define a huge aggregate consisting of a Customer and all her Orders, we can just keep the relation between both entities thru an identifier reference. By doing this, we avoid loading all the Orders when fetching a Customer as well as we mitigate concurrency problems.
But, say that now business defines the next invariant:
We want to provide Customers with a pocket so they can charge it with money to buy products. Therefore, if a Customer now wants to buy a product, it needs to have enough money to do it.
Said so, pocket is a VO inside the Customer Aggregate Root. It seems now that having two separated Aggregate Roots, one for Customer and another one for Order is not the best to satisfy the new invariant because we could save a new order without checking the rule. Looks like we are forced to consider Customer as the root. That is going to affect our performance, scalaibility and concurrency issues, etc.
Solution? Eventual Consistency. What if we allow the customer to buy the product? that is, having an Aggregate Root for Orders so we create the order and save it:
var newOrder = new Order(customerId, ...);
orderRepository.save(newOrder);
we publish an event when the order is created and then we check asynchronously if the customer has enough funds:
class OrderWasCreatedListener:
var customer = customerRepository.findOfId(event.customerId);
var order = orderRepository.findOfId(event.orderId);
customer.placeOrder(order); //Check business rules
customerRepository.save(customer);
If everything was good, we have satisfied our invariants while keeping our design as we wanted at the beginning modifying just one Aggregate Root per request. Otherwise, we will send an email to the customer telling her about the insufficient funds issue. We can take advance of it by adding to the email alternatives options she can purchase with her current budget as well as encourage her to charge the pocket.
Take into account that the UI can help us to avoid having customers paying without enough money, but we cannot blindly trust on the UI.
Hope you find both examples useful, and let me know if you find better solutions for the exposed scenarios :-)
In this sort of cases, could it mean that I need to redesign and re-think my aggregates?
Almost certainly.
The driver for aggregate design isn't structure, but behavior. We don't care that "a user has thousands of orders". What we care about are what pieces of state need to be checked when you try to process a change - what data do you need to load to know if a change is valid.
Typically, you'll come to realize that changing an order doesn't (or shouldn't) depend on the state of other orders in the system, which is a good indication that two different orders should not be part of the same aggregate.

Aggreate Root, Aggregates, Entities, Value Objects

I'm struggling with some implementation details when looking at the terms mentioned in the title above.
Can someone tell me whether my interpretation is right?
For reference I look at a CRM Domain
As a AggregateRoot I could see a Customer.
It may have Entities like Address which contains street, postal code and so on.
Now there is something like Contact and Activity this should be at least aggregates. Right? Now if the Contacts and Activities would have complex business logic. For example, "Every time a contact of the type order is created, the order workflow should be started"
Would then Contact need to be an Aggregate root? What may be implementation implications that could result from this?
Further more when looking and Event Sourcing, Would each Aggregate have its own Stream? In this scenario A Customer could have thousands of activities.
It would be great if someone could guide em in which part my understanding is right and which I differ form the common interpretation.
What do you mean by “at least aggregates”?
An aggregate is a set of one or more connected entities. The aggregate can only be accessed from its root entity, also called the aggregate root. The aggregate defines the transactional boundaries for the entities which must be preserved at all time. Jimmy Bogard has a good explanation of aggregates here.
When using event sourcing each aggregate should have its own stream. The stream is used to construct the aggregates and there is no reason to let several aggregates use the same stream.
You should try to keep your aggregates small. If you expect your customer object to have thousands of activities then you should look at if it is possible to design the activities as a separate aggregate, just as long as its boundaries ensures that you do not leave the system in an invalid state.

Core data relationship confusion

I'm making a core data model, and I have a Client entity that has a to-many relationship to an Appointment entity. An Appointment can turn into a Transaction (if it has been paid for etc.), and I need to keep track of the Appointments of Clients that have turned into Transactions (where Transaction is an entity along with other attributes). A Client can have multiple Transactions, and a Transaction can have multiple Clients (optional). If I put a relationship between Transaction and Client, then I don't think there's a way I can detect which of the appointments have turned into transactions and which haven't...
Any help as to how I can set my model up to do this would be appreciated.
Thanks
I think there are more than one way of doing it. This is one I think works:
If Transaction is another entity, and Appointment has a one-to-one relationship to Transaction. Then you can leave the Transaction entity to be nil if unpaid. If paid, you set up Transaction and link up with its relationship to Appointment and Client. By checking if your Appointment's Transaction is nil, you know if it's turned into Transaction or not.
If you need detailed information about the transformation between the appointment and transaction you could make that transformation itself an entity and make it persistent. The new transform entity could have various properties like:
date (when did the transformation happened)
type (did the appointment transform into a transaction, was canceled or delayed)
etc
and relations:
from (the original appointment)
to (the resulting transaction/appointment/etc)
This way the relation between client and translation would look like this
Client->Appointent->Transform->Transaction
If the only difference between Appointent and Transaction is being paid or not, you can consider using only Transaction and a flag (paid/not paid).
Client->Transaction->Transform->Transaction

Resources