I am wondering how granular should a domain event be?
For example I have something simple, like changing the firstName, the secondName and the email address on a profile page. Should I have 3 different domain events or just a single one?
By coarse grained domain events when I add a new feature, I have to create a new version of the event, so I have to add a new event type, or store event versions in the event storage. By fine grained domain events I don't have these problems, but I have too many small classes. What do you think, what is the best practice in this case?
What's the problem with many classes? Really, why so many devs are afraid of having too many classes? You define as many classes as needed.
A domain event signals that the domain changed in a certain way. It should contain all the relevant information and it should be taken into consideration the fact that an event is also a DTO. You want clear events but it's up to the developer to decide how granular or generic an event is.
Size is not a concern, however if your event 'weights' 1 MB maybe you have a problem. And the number of classes is not a domain event design criteria.
I can agree with MikeSW's answer, but applying SRP during the modeling, you can end up with small classes, which is not a problem at all.
According to Greg Young the domain events should always express something that the user does from a business perspective. For example if the user has 2 reasons to change her phone number PhoneNumberChanged, and this information can be important from a business perspective, then we should create 2 event types PhoneNumberMigrated, PhoneNumberCorrected to store technically the same data. This clearly violates DRY, but that is not a problem, because SRP can override DRY in these cases as it does by sharing aggregates and their properties (most frequently the aggregate id) between multiple bounded contexts.
In my example:
I have something simple, like changing the firstName, the
secondName and the email address on a profile page.
We should ask the following: why would the user want that, has it any importance from the perspective of our business?
her account was stolen (security, not business issue)
she moved to another email address
she got married
she hated her previous name
she gave the account to somebody else on purpose
etc...
Well, if we have dating agency services then logging divorces can have probably a business importance. So if this information is really important, then we should put that it into the domain model, and create an UserProbablyDivorced event. If none of them are important, then we can simple say, that she just wanted to change her profile page, we don't care why, so I think in that case both UserProfileChanged or UserSecondNameChanged events can be acceptable.
The domain events can be in 1:1 and in 1:n relation with the commands. By 1:1 relation they name is usually the same as of the commands, but in a past tense. For example ChangeUserProfile -> UserProfileChanged. By 1:n relation we usually split up the behavior which the command represents into a series of smaller domain events.
So to summarize, it is the domain developer's decision how granular the domain events should be, but it should by clearly influenced from a business perspective and not just from a modeling a data schema perspective. But I think this is evident, because we are modeling business and not just data structure.
Related
I am trying to design a use case diagram for the following scenario.
I have a society that is distributing goods to clients based on their orders. These clients can be administrations, companies, or private individuals.
Depending on what the client is I want to know more or less of their info (name, number etc)
The use cases are different depending on whether the client is:
English
English and have used this service for more than 3 years
Foreign
For example:
The 1) English clients' orders are accepted only if they pay a small fee in advance.
The 2) English clients that have used the service for 3 years don't have to pay this fee but need to get approbation from a different actor (an Agent in this case)
The 3) Foreign clients' orders are always accepted no matter what.
This right here is where I run into trouble and need help with.
The orders from nglish clients that have a criminal record are always denied UNLESS they are an administration.
What are the most optimal actor choices here? I thought of going with English client, and Foreign clients but I don't know how to include the "Unless the client is an administration" in the use case.
The use case diagram is not the right place to put this information. As correctly pointed out by #Christophe, a use-case represents a goal for a user who is going to interact with the system to achieve the goal.
This means that there is only one single use case in your scenario: "Order Goods". However, it has a set of preconditions. You could list them as structured plain text. Since there is quite some complexity behind each of them, I recommend to put them into a separate decision chart. Then you have a nice clean separation of the diagram scopes, and they remain easily readable.
Sidenote: There could be a second one "distribute ordered goods" executed by a 2nd actor who is an employee who does fulfillment / routing / dispatching.
Actors in UML use-cases are classifiers. To decide about which actors to create requires to understand the actors their goals and behaviours and how they differ in the interaction with the system.
First of all, you need to clarify the super-ambiguous requirements:
"English client": is this a client with English nationality? Is it a client that lives permanently in the UK? Is this a client with an address in the UK? Is it a client with a +44 phone number?
"Foreign client": same kind of questions + can you define for sure the difference between Ensglish and Foreign? For example: what with bi-nationals? what with people having two addresses one being abroad?
"Using this service more than three years": what with a foreign customer who uses the service for 3 years and then settles in the UK?
Since you deliver goods, you might also need to consider a delivery address. What with an English client ordering on a foreign address or vis-versa ?
"criminal record": the criminal record might change over time: is it provided at each purchase? or is it part of the customer registration process ? In the latter case, is there a need to periodically renew this information ?
Use-cases should in principle be goal oriented. So a use-case represents a goal for a user who is going to interact with the system to achieve the goal. Use-cases are not meant to describe the detailed sequence of your process (if client is this, do that, etc...) and neither are actors meant for that purpose.
You should therefore consider reformulating the use-cases to represent how the actors would perceive them. If needed you may consider the status of the actor that could explain that an actor behaves very differently. Typically in your case, I could imagine :
New client: a new client may want to provide details (address, identification) or evidence that they are entitled to buy (criminal record - I suppose your activity is regulated if you request such details)
Public administration: behavior of administration in purchase is anyway different because of public procurement and legal constraints.
Privately owned company: behavior is different since it can involve several persons,
Private individual
The need to pay an advance fee seem to depend on the address, nationality, history. It's more related to the process (it's a part of it) than an independent goal for an actor. So I would neither show this as a use-case nor make different actors for this purpose.
The reason to deny an order is not something that is not relevant for the customer (no customer has a goal go get a purchase denied!). It's relevant to you and your system and is a consequence of the registration process. So no need to have a dedicated actor for that.
I am trying to utilize some DDD approaches in the app that allows guest purchase. While it looks easy, I got a bit confused and asking for your DDD advice.
The app has several bounded contexts and we are looking at 3 of them:
Customers (customers manage their user settings here, authentication, also admin can potentially create users)
Sales (orders)
Billing (charging customers for one-off payments and subscriptions)
The user story:
As a guest I want to order the product to do something.
This is one form and on checkout he/she will be asked for email and password. We need to create account on this step, but based on business logic this fits to Sales context - guest makes an order. We actually need to do simple steps:
Create user with ACTIVE status
Store billing details
Create order
Charge user later (event handled by Billing)
The confusion here is that it requires creating a user first. It looks more naturally to create it in customers, but probably it’s wrong? User can not sign up in any other way - only by placing an order, but admin can create a user manually. Based on different system events(from different contexts), the Customer context may change the user status based on special logic that is placed into Customer domain. Is there any safe way for sharing this User status logic between different contexts (while creating User in Sales we need that status enum class)? Does this logic for placing order look ok? Could you please recommend another approach if you think that this one is wrong?
Status is DDD at its worst. Including a status field is 1) lazy, and yet 2) very convenient. Yes, one of those design trade offs.
When you assign a status or read a status you are ignoring or sublimating significant business logic and structure for your domain. When “status” changes some very significant changes could occur in your domain... way beyond changing a status property.
Throw status out and instead consider some concepts: a CasualShopper or Guest (no purchases, browsing for products), a PotentialNewShopper (someone adding things in their basket who you’ve never seen before), and your usual Customer (which should probably be subdivided based on their current activity).
With this modeled, you can attach behaviors directly to each of these objects and “status” itself is sublimated into a richer DDD model. A common DDD mistake is not creating a transactionally-significant object (e.g. a Potential Shopper role) for some static/non-temporal object (e.g. a person).
From here you may decide you need a few bounded contexts; perhaps PotentialCustomers and EstablishedCustomers. In each the set of domain transitions are different and can be encapsulated rather than externalized.
So...
With that out of the way it looks like you have a Customer BC and a PossibleCustomer BC. You can safely do what you need to do in the latter now that it is self-contained.
Oh, but that may affect billing! and ordering!
True. That may mean new BCs or new objects in those BCs such as ProvisionalPayment and UnauthenticatedOrder. I’m spitballing a bit now...
My point is you have events that can transition between states rather than encoding those states, and as such you can attach the behaviors you need and persist them as needed in some physical store, that is likely partitioned in a way suitable to your DDD.
Doing all this work means not sharing unsafe status but sharing safe projections of relevant objects only.
Jumping into implementation briefly and anecdotally, developers are loath to store “temporary” state. “Temporary” state is OK to store and necessary when you’re modeling a domain without that cruddy status field.
You probably should ask yourself first whether you got the Bounded Contexts right.
In my opinion you have the following BCs
Identity and Users
Sales and Billing
consider this: the same person is a User in the first context but a Customer in the latter. so you have two views on the same real world entity which suggests that you have two bounded contexts where this entity means different things.
your bcs sound more like modules in the Sales and Billing context.
If you agree, then the control flow for your problem may be simplified where an entity in one context is created and the creation is propagated via event into the other. so the initial request could be handled by the Sales bc and the guest user handling would be propagated to Identity.
I am new to DDD. Now I was looking at the domain event. I am not sure if I understand this domain event correctly, but I am just thinking what will happen if domain event published failed?
I have a case here. When a buyer order something from my website, firstly we will create a object, Order with line of items. The domain event, OrderWasMade, will be published to deduct the stock in Inventory. So here is the case, what if when the event was handled, the item quantity will be deducted, but what if when the system try to deduct the stock, it found out that there is no stock remaining for the item (amount = 0). So, the item amount can't be deducted but the order had already being committed.
Will this kind of scenario happen?
Sorry to have squeeze in 2 other questions here.
It seems like each event will be in its own transaction scope, which means the system requires to open multiple connection to database at once. So if I am using IIS Server, I must enable DTC, am I correct?
Is there any relationship between domain-events and domain-services?
A domain event never fails because it's a notification of things that happened (note the past tense). But the operation which will generate that event might fail and the event won't be generated.
The scenario you told us shows that you're not really doing DDD, you're doing CRUD using DDD words. Yes, I know you're new to it, don't worry, everybody misunderstood DDD until they got it (but it might take some time and plenty of practice).
DDD is about identifying the domain model abstraction, which is not code. Code is when you're implementing that abstraction. It's very obvious you haven't done the proper modelling, because the domain expert should tell you what happens if products are out of stock.
Next, there's no db/acid transactions at this level. Those are an implementation detail. The way DDD works is identifying where the business needs things to be consistent together and that's called an aggregate.
The order was submitted and this where that use case stops. When you publish the OrderWasMadeevent, another use case (deducting the inventory or whatever) is triggered. This is a different business scenario related but not part of "submit order". If there isn't enough stock then another event is published NotEnoughInventory and another use case will be triggered. We follow the business here and we identify each step that the business does in order to fulfill the order.
The art of DDD consists in understanding and identifying granular business functionality, the involved aggregates, business behaviour which makes decisions etc and this has nothing to do the database or transactions.
In DDD the aggregate is the only place where a unit of work needs to be used.
To answer your questions:
It seems like each event will be in its own transaction scope, which means the system requires to open multiple connection to database at once. So if I am using IIS Server, I must enable DTC, am I correct?
No, transactions,events and distributed transactions are different things. IIS is a web server, I think you want to say SqlServer. You're always opening multiple connections to the db in a web app, DTC has nothing to do with it. Actually, the question tells me that you need to read a lot more about DDD and not just Evans' book. To be honest, from a DDD pov it doesn't make much sense what you're asking.. You know one of principles of DD: the db (as in persistence details) doesn't exist.
Is there any relationship between domain-events and domain-services
They're both part of the domain but they have different roles:
Domain events tell the world that something changed in the domain
Domain services encapsulate domain behaviour which doesn't have its own persisted state (like Calculate Tax)
Usually an application service (which acts as a host for a business use case) will use a domain service to verify constraints or to gather data required to change an aggregate which in turn will generate one or more events. Aggregates are the ones persisted and always, an aggregate is persisted in an atomic manner i.e db transaction / unit of work.
what will happen if domain event published failed?
MikeSW already described this - publishing the event (which is to say, making it part of the history) is a separate concern from consuming the event.
what if when the system try to deduct the stock, it found out that there is no stock remaining for the item (amount = 0). So, the item amount can't be deducted but the order had already being committed.
Will this kind of scenario happen?
So the DDD answer is: ask your domain experts!
If you sit down with your domain experts, and explore the ubiquitous language, you are likely to discover that this is a well understood exception to the happy path for ordering, with an understood mitigation ("we mark the status of the order as pending, and we check to see if we've already ordered more inventory from the supplier..."). This is basically a requirements discovery exercise.
And when you understand these requirements, you go do it.
Go do it typically means a "saga" (a somewhat misleading and overloaded use of the term); a business process/workflow/state machine implementation that keeps track of what is going on.
Using your example: OrderWasMade triggers an OrderFulfillment process, which tracks the "state" of the order. There might be an "AwaitingInventory" state where OrderFulfillment parks until the next delivery from the supplier, for example.
Recommended reading:
http://udidahan.com/2010/08/31/race-conditions-dont-exist/
http://udidahan.com/2009/04/20/saga-persistence-and-event-driven-architectures/
http://joshkodroff.com/blog/2015/08/21/an-elegant-abandoned-cart-email-using-nservicebus/
If you need the stock to be immediately consistent at all times, a common way of handling this in event sourced systems (can also in non-event based systems, this is orthogonal really) is to rely on optimistic locking at the event store level.
Events basically have a revision number that they expect the stream of events to be at to take effect. Once the event hits the persistent store, its revision number is checked against the real stream number and if they don't match, a conflict exception is raised and the transaction is aborted.
Now as #MikeSW pointed out, depending on your business requirements, stock checking can be an out-of-band process that handles the problem in an eventually consistent way. Eventually can range from milliseconds if another part of the process takes over immediately, to hours if an email is sent with human action needing to be taken.
In other words, if your domain requires it, you can choose to trade this sequence of events
(OrderAbortedOutOfStock)
for
(OrderMade, <-- Some amount of time --> OrderAbortedOutOfStock)
which amounts to the same aggregate state in the end
I have an assignment for school, where I have to create a domain model of a specific e-commerce site that delivers complete grocery bags to people's homes. (http://www.linasmatkasse.se/)
It's quite basic. Chose a bag, create account (with info), pay.
My question is, what exactly should be included in the model (in general)? In other words, where does the lines of the domain end? For instance, should delivery and suppliers be included? They aren't technically part of the website itself, by still play a role.
Thanks in advance!
What is domain
Let us take some theme/subject. It could be grocery delivery, satellites, swallows observations, anything. Let us name this theme "AAA"
domain model for AAA is a "profi IT" word for model for AAA. That's all.
All elements specific to AAA that you'll set in your model, belong to domain. I don't know, why the old good word theme is not used. It is a pity. But the term is already accepted.
So, delivery and suppliers are in your domain. And also much more specific words belonging to grocery. And to bags. And to people's homes - addresses, drive ways in and out - everything that is relevant to your theme.
The domain sets your vocabulary. And that one is really important - you should use the vocabulary used by your clients and not to invent new words, such as "domain" for "theme" :-)
And first you should define your Use case diagram, later- State machine diagram, Deployment diagram, Component diagram, Communication diagram, Sequence/Activity/Time/Interaction Overview diagrams, and at last - class, object and composite structure diagrams. You needn't make all of them, but SOME are necessary.
Every entity that models an entity in reality is a part of the domain. In your example, delivery and suppliers should be a part of the domain model. Basically any entity that has a defined behavior should be modeled as a part of the domain. Many times it seems like the domain model components aren't a part of the website and this is actually normal, the front-end is a way of viewing the domain model, it doesn't need to expose everything within the domain.
I usually find it easy to think about what entities are logical components of the business model in the real world and I only remove one if I find that it is redundant, unnecessary or can be encapsulated within another entity.
About the entities that are not the part of IT system
Do not ignore the pure human operations. On the contrary. Put them here, only their use cases will connect not actor-(sub)system, but actor-actor. And seeing them is very good for better planning the system as a whole. When ignoring them it is impossible to create a system good for user. The IT system is an integral component of the larger system, and we are creating the larger one really, with planning the support, processes, exchange of info, divisions and dependencies.
Too often had I problems with programmers who are blind to anything out of IT system border. And often it is impossible to make them think out of these borders. As a result, the system is blind to the real needs of the user, too. So we have that sad picture of user-hating software.
It is very useful to start to study the problem/domain/theme from entities that are out of the IT system, and to create firstly the diagram, that considers IT system as merely one of many blocks.
I have a scenario where a customer calls and gets an appointment at a garage. When drawing a UML Use Case Diagram, is the actor who is connected to placing this appointment inside the system (a) the customer, or (b) the employee?
The person that has their fingers on the keyboard and mouse is the actor. The person calling in is important from a business perspective, but not as important as the customer service rep that is interacting with the system.
Knowing that the actor is a CSR helps the screen designer and even the developer, because they will work from that perspective, ask for requirements or design clarifications from that perspective, and the system will be better as a result.
The reason the conflict exisits is because of the point of the project when you start drawing these use cases.
In your example, you already know that there is a CSR using 'a system' to make the booking.
However the design could have started from scractch. If this had happened the initial broad use case would have been 'a customer wishes to make a booking'. This could have lead to a number of differenc cases i.e. a customer will call a telephone number and an automated service will make the booking, a customer arrives at the garage and uses a terminal to make a booking or (as in your case) talks to a CSR (however that is i.e. phone or face2face) and they make the booking.
In many examples the customer would be the main actor in the system. However in your design the CSR is the one holding the mouse/keyboard/phone/pen or whatever and you don't need to design the iteraction between the customer and the CSR! Most societies did that years ago :)
It can be both. It depends. There is no single good way to model this. I would personally opt for the customer.
It is btw perfectly alright to include the phone as part of your system. So the boundary of a system does not have to be a defined by screen, mouse, keyboard. A printer might be included too as part of the system. I have written use case where it was quite essential that users printed some information and file that.
Who is the important actor here? The customer right? It is interesting to note here that Alistair Cockburn extended the actor and goals model of Ivar Jacobson with the actors and 'interests' model. His advice is to also think about who cares (or gets hurt) if user goal fails.
Is it important to get the actor just right? It is useful to brainstorm actors to find all user goals against the system. When you are confident you have found all goals, the actor is not so important anymore. Would you 'write' a completely different use case depending on this decision? Would a different system be build based on the outcome of this decision?
Who initiates the interaction? What is the event initiates it? This event is the decision of customer to call to make an appointment.
You could model customer as primary and employee as secondary actor helping customer to reach user goal. Both use phone and system to reach the goal, customer helped by employee. How they do that exactly is design?
Another consideration is that the 'actor' is a role. So you could use a role Appointment Maker. Some people care a lot about keeping job titles separate from roles as there typically some flexibility in roles that job titles perform.
There are also people who are of opinion that use of 'system' in describing use case is undesirable. They feel that it is a design/implementation decision and so they prefer more neutral 'Performer'. The Performer could be a system but also a human. In use case texts they use 'Initiator' and 'Performer' and in introduction of the use case text they explain that the 'Initiator' is in use case the Appointment Maker.
I personally think it would be fine and better if the use case was described as if customer was the one operating the system. The employee is just passing along information from system to customer and vice versa.
The book by Alistair Cockburn is a recommended read. His insights really helped me with questions like this one. It also helps to make sense of UML in relation to use case