I got a command : MovePlayerCommand.
One of the validator for this command does 3 things :
calculate the cost for the player to move (can be called for validation but also for displaying purpose)
validate this cost
listen to the "PlayerMoved" event so we can apply the costs (for instance - 10 action point).
Is this too much responsibilities for a single class ? If so how would you separate this ?
Edit : I know that removing the cost and checking it are 2 things, but I cant separate them from the computing of this costs, and I don't want to have 3 classes for each Action
There is a big misunderstanding here, as some poeple making comments seem to be mixing DDD and CQRS. The OP is talking about commands and has tagged the question with cqrs, so I am going to assume that the OP is indeed using DDD with CQRS.
The domain validation logic should be in the command handler, you can do, and indeed should do data checking before the command hits the handler stub, but not do any domain logic validation. That said, there is no other place where you could validate the command against the domain logic other than in the command handler because that is the place where your aggregates are loaded.
The validations you are showing are domain validations, so they should be actually performed by your aggregate, so yes, I think you should break that responsibility a bit, and split the different types of validation: data and domain.
Impossible to answer definitively without a lot more information.
That said, what you described does not sound like a validator; it sounds like a "calculator" of sorts.
It's likely that the calculating methods would belong in one class (the calculator class), and the validator class would then reference the calculator.
I tend to handle domain events in a very thin handler class, which then defers to an aggregate root or service (this is a common but not universal practice). So the root or service would likely also have a reference to the calculator (and possibly the validator).
This question may be too broad for SO, and might be better answered on a DDD forum. Even then, you may need to provide more background.
Related
My question here is quite straight as mentioned in the subject.
However, please allow me to give some brief explanation here about my innocent thoughts.
I've been using Axon for approximately 10 months now. I used to design my project structure based on the Hexagonal architecture with two top level packages respectively for domain and infrastructure.
Furthermore, domain package will contain different domain objects (as explained in the DDD concept) such as follow:
Aggregate (this will be an Axon aggregate class).
Repository (in my case, this will be a Spring Data Repository interface).
Entity (in my case, this contains any lookup entity that i used for set-based consistency validation as written here).
Service Port (collection of Input and Ouput port interfaces).
Commands (representing Axon Command object).
As for Events, I used to put them on a different module that I compiled as a jar file, so I can share it to other developers whom going to use the same event in their project.
I've noticed recently that all of my commands and events were basically anemic models (an anti pattern that we should avoid).
Is there any good practice on this ? Or, Is it something that intentionally used by design ?
I've been thinking to put my Command classes within my Aggregate class (as an inner classes). At least by using this approach I won't end-up with having so many anemic models scattered outside. Any thoughts ?
Commands are designed to be behavior and input structures mirroring the external world. They don't necessarily mirror an aggregate's structure.
They are not even connected clearly to one single aggregate, at times. Enclosing them within aggregates can be a code smell because you are then thinking in terms of resources and UI organization, instead of transaction boundaries and entity groups.
You are also violating the open-closed principle. Changes in volatile layers like user interface and request structures will make you edit the Aggregate class, and that is not good design.
On a more general note...
At times, this debate of anemic vs. non-anemic (or dry vs. non-dry) can push you in the direction of premature - and incorrect - optimization. Try avoiding this trap because you will end up optimising at the code level, but your domain will suffer.
DDD and CQRS guidelines align with principles that help you keep complexity at bay over the long term. Things kept distinct and separate help you achieve this.
First of all, in DDD, your domain had to be free of any frameworks, just use pure language library.
Then, mixing Commands and Aggregates cannot be a good solution. I think Commands belongs to Port while Aggregates belongs to the Hexagone.
Finally, DDD highlights the discovery of the domain thanks to the experts. Did you do that ? If not, if you're only using the Tacticts pattern, you'll miss one of the most important part of DDD.
Iam building bounded context using CQRS pattern. I prepared some queries and handlers for each. And now, in presentation layer(http REST controller) I have to use it. Question is, should I inject each handler to this controller (there is 4 queries and handlers) or use command bus and configure right handlers to specified query?
Well, either way seems like it makes sense; that's probably a hint that you should be passing in an interface that expresses the contract that the Controller needs satisfied, and punt the implementation details down a level.
My guess is that you ultimately won't want the controller directly wired into the query handlers, because that will restrict your options in a number of use cases (example: congestion control and back pressure). But you won't know until much further down the road, so keep things loose.
In the past we've injected some sort of Query Executor into the controller and passed queries into that. eg,
public SomeController(IQueryExecutor queryExecutor) { ...
and then
var results = queryExecutor.Query(new GetSomeThings(args..));
The handler for GetSomeThings is wired up by the supporting infrastructure so you don't need to inject those. Does that make sense?
A word of warning about CQRS/CQS:
If you find you writing queries and handlers that are used at most only once or twice, or commands that are dedicated to the controller that uses them, then perhaps CQRS/CQS is an abstraction you don't actually need to be paying the extra complexity cost for.
My teams and I have found this to be true on a number of projects. Often CQRS/CQS is just another unnecessary abstraction like a Repository which dispatches to an ORM lib or a 'Service' which has one or two line dispatches to a Repository, which...
Hopefully you get the point.
I like the Rule Of Three - don't try to get reusability until you have more than 3 usages. And even then, don't jump deep into something heavy and very prescribed like CQRS/CQS if you don't need it. DDD is very kool but you can pick and choose which elements of it make sense for you. Often much of it won't make sense when you apply pragmatic reasoning.
Just my 2 c.
Suppose there is a scenario of Users having Tasks. Each User can either be a Watcher or Worker of a Task.
Furthermore, a Worker can file the hours he has worked on a given Task.
Would the following diagram be correct? I have looked around at domain models and I have not seen one with the two associations (works on, watches). Is it acceptable?
EDIT: What about this scenario? An User can make an Offer to another user. A possible way of modelling it is shown on the following diagram.
However, in that diagram it would seem possible for a user to make the offer to himself. Is it possible to model some constraints in, or is this handled further down the development line?
It is in principle correct, this is how you model multiple relationships between two classes.
As for the constraints, UML makes use of OCL (Object Constraint Language), so you can say that the associations are exclusive (xor - exclusive or).
Also note that it is generally a good idea to name the end roles of the associations.
Regarding one of the comments saying
There are no UML police to flag you down for being "unacceptable".
It is like saying: there's no code police to flag you down for writing shitty code.
You create diagrams to convey information (for school project anyway), if you diverge from standards or best practices you make it harder for other people to understand your diagrams.
And just like there are linters (jslint, ...) that check your code for common problems, for models there are model validations that do the same thing.
Also models, just like code, aren't set in stone so don't be afraid to modify them when you find a better way to express your domain.
Update
As Jim aptly pointed out, you usually do stuff not as a User (or Person), but as a Role. E.g. when you are student and you are filling a form, nobody cares that you are human, but that you are a Student. Typically a Person will also have several different roles (you could be a Student and a TA, a Professor, etc.)
Separating it in this way makes the domain much clearer as you are concerned only with the Roles, and not the people implementing them.
On the first model, there's not much to add after Peter's excellent and very interesting answer.
However your second diagram (in the edit section) does seem to give a true and fair view of the narative. From the strict 1 to 1 relationships, I'd understand that every user makes exactly one offer to one other user, and every user receives exactly one offer from another user:
"A user can make an offer to another user" implies a cardinality of 0..1 or *, not 1.
From this we understand implicitly that not all users need to receive an offer, i.e. also a cardinality of 0..1 or *
This can be debated, but "an offer" doesn't in my opinion mean at "at most one offer", so the upper bounds of cardinality shouldn't be * and not 1 to show that every user may make several offers and receive several offers.
As you can see, you can add constraints to the schema to increase expressivity. This is done in an annotation between { } . But you can choose the most suitable syntax. Here an example with the full expressivity of natural language (as suggested by Martin Fowler in his "UML distilled") but you can of course use the more formal OCL, making it {self.offerer<>self.offeree}.
I see #Peter updated his answer before I could post this answer, but I will post this anyway to show you some other tricks.
In general, it is perfectly valid to have multiple associations between the same two classes. However, I don't think it's a good idea here.
You say you want to build a [problem] domain model. I'm glad to hear that! A problem domain model is very important, as I explain in the last paragraph here. One thing to point out is that you want to build a durable model that transcends a system you can conceive. In the problem domain, there is no "User". There are, however, Roles that People play. For example, you mentioned Watcher and Worker. Hopefully these are concepts your customer already has in the "meat world".
In the model you posted, you have no place to hang the hours worked or progress made. You might try an exercise. If you had no computer, how would your customer track these things? They often have (or had) a way, and it was probably pretty optimal for a manual system.
Here is how I would model my understanding of your problem domain:
Some things to note:
A Person plays any number of Roles.
A Role is with respect to exactly one Task and one Person. A Watcher watches exactly one Task, a Worker is assigned to exactly one Task, and any kind of Role is played by exactly one Person.
A Role is abstract, and its subclasses are {complete}, meaning there can be no valid instance of a Role without also being an instance of a subclass.
A Task is watched by any number of Watchers and may be assigned to one Worker at a time. There is a constraint saying {person is not a watcher}. (You can show the OCL for that, but few people will understand it.)
I have added a Progress concept as a way of logging progress on a Task. A Worker makes Progress on one Task. Each bit of Progress has a Description and a Duration. Note that I have not committed to any computational way of representing a Description or a Duration. The designer of a system for this will be free to derive a Duration from start and end times, or ask the user to self-report.
We all heard that injecting repository into aggregate is a bad idea, but almost no one tells why.
I will try to write here all disadvantages of doing this, so we can measure rightness of this statement.
First thing that comes into my head is Single Responsibility Principle.
It's true that by injecting repository into AR we are violating SRP, because retrieving and persisting of aggregate is not responsibility of aggregate itself. But it says only about "aggregate itself", not about other aggregates. So does it apply for retrieving from repository aggregates referenced by id? And what about storing them?
I used to think that aggregate shouldn't even know that there is some sort of persistence in system, because it doesn't have to exist. Aggregates can be created just for one procedure call and then get rid of.
Now when I think of it, it's not right, because aggregate root is an entity, and entity has sense only if it has some unique identity. So why would we need unique identity if not for persisting? Even if it's just a persistence in a memory. Maybe for comparing, but in my opinion it's not a main reason behind the identity.
Ok, let's assume that we retrieve and store OTHER aggregates from inside of our aggregate using injected repositories. What are other consequences beside SRP violation?
For sure there is a problem with having no control over persisting of aggregates and retrieving is some kind of lazy loading, which is bad for the same reason (no control).
Because of no control we can come into situation when we persist the same aggregate few times, where it could be persisted only once, or the same aggregate is loaded one hundred times where it could be loaded once, hence performance is worse. Also there might be problem with stale data.
These reasons practically disqualifies ability to inject repository into aggregate.
Here comes my main question - why can we inject repositories into domain service then?
Not the same reasons applies here? It's just like moving logic out of aggregate into separate function and pretend it to be something different.
To be honest, when I stared to write this SO question, I had no good answer for that. But after hours of investigating this problem and writing of this question I came to solution. Rubber duck debugging.
I'll post this question anyway for others having the same problems. Of course with my answer below.
Here are the places where I'd recommend to fetch aggregates (i.e. call Repository.Get...()), in preference order :
Application Service
Domain Service
Aggregate
We don't want Aggregates to fetch other Aggregates most of the time, because this blurs the lines, giving them orchestration powers which normally belong to the Application layer. You also raise the risk of the Aggregate trespassing its jurisdiction by modifying other Aggregates, which can result in contention and performance problems, not to mention that transactions become more difficult to analyze and the code base to reason about.
Domain Services are IMO a good place to fetch Aggregates when determining which aggregates to modify is domain logic per se. In your game example (which might not be the ideal context for DDD by the way), which units are affected by another unit's attack might be considered domain logic, thus you may not want to place it at the Application Service level. This rarely happens in my experience though.
Finally, Application Services are the default place where I call Repository.Get(...) for uniformity's sake and because this is the natural place to get a hold of the actors of the use case (usually only one Aggregate per transaction) and orchestrate calls to them.
That doesn't mean Aggregates should never be injected Repositories, there are exceptions, but other alternatives are almost always better.
So as I wrote in a question, I've found my answer already in the process of writing that question.
The best way to show this is by example:
When we have a simple (superficially) behavior like unit attacking other unit, we can write something like that.
unit.attack_unit(other_unit)
Problem is that, to attack an unit, we have to calculate damage and to do that we need another aggregates, like weapon and armor, which are referenced by id inside of unit. Since we cannot inject repository inside of aggregate, then we have to move that attack_unit logic into domain service, because we can inject repository there. Now where is the difference between injecting it into domain service, and not into unit aggregate.
Answer is - there is no difference. All consequences I described in question won't bite us. In both cases we will load both units once, attacking unit weapon once and armor of unit being attacked once. Also there won't be stale data, even if we mutate weapon object during process and store it, because that weapon is retrieved and stored in one place.
Problem shows up in different example.
Lets create an use case where unit can attack all other units in game in one process.
Problem lies in how we implement it. If we will use already defined unit.attack_unit and we will call it on all units in game (iterating over them), then weapon that is used to compute damage will be retrieved from unit aggregate, number of times equal to count of units in game! But it could be retrieved only once!
It doesn't matter if unit.attack_unit will be method of unit aggregate, or if it will be domain service unit_attack_unit. It will be still the same, weapon will be loaded too many times. To fix that we simply have to change implementation and with that probably interface too.
Now at least we have an answer to question "does moving logic from aggregate method to domain service (because we want to access repository there) fixes problem?". No, it does not change a thing.
Injecting repositories into domain service can be as dangerous as injecting it into aggregate if used wrong.
This answers my SO question, but we still don't have solution to real problem.
What can we do if we have two use cases: one where unit attacks one other unit, and second where unit attacks all other units, without duplicating domain logic.
One way is to put all needed aggregates as parameters to our aggregate method.
unit.attack_unit(unit, weapon, armor)
But what if we will need like five or more aggregates there? It's not a good way. Also application logic will have to know that all these aggregates are needed for an attack, which is knowledge leak. When attack_unit implementation will change we would also might to update interface of that method. What is the purpose of encapsulation then?
So, if we can't access repository to get needed aggregate, how can we smuggle it then?
We can get rid of idea with referencing aggregates by ids, or pass all needed aggregates from application layer (which means knowledge leak).
Or maybe reason of these problems is bad modelling?
Attacking of other unit is indeed an unit responsibility, but is damage calculation its responsibility? Of course not.
Maybe we need another object, like value object MeleeAttack(weapon, armor), yet when we add more properties that can change result of an attack, like enchantments on unit, it gets more complicated.
Also I think that we are now creating objects based on performance, not our on domain.
So from domain driven design, we get performance driven design. Is that what we want? I don't think so.
"So why would we need unique identity if not for persisting?" - think of an account scenario, where several John Smiths exist in your system. Imagine John Smith and John Smith Jr (who didn't enter the Jr in signup) both live at the same address. How do you tell them apart? Imagine I'm trying to write a recommendation engine based upon their past purchases . . . .
Identity is a quality of equality in DDD. If you don't have an identity unique from your fields, then you're a ValueObject.
What are consequences of using repository inside of aggregate vs inside of domain service?
There's a reasonably strong argument that you shouldn't do either.
Riddle: when does an aggregate need to see the state of another aggregate?
The responsibility of an aggregate is to control change. Any command that would change the state of the domain model is dispatched to the aggregate root responsible for the integrity of the state in question. By definition, all of the state required to ensure that the command is currently permitted is contained within the aggregate boundary.
So there is never any need to peek at the data outside of the aggregate when making a change to the model.
In which case, you don't ever need to load another aggregate, which makes the "where" question moot.
Two clarifications:
Queries will often combine the state of multiple aggregates, and will often need to follow a reference from one aggregate to another. The principle above is satisfied because queries treat the domain model as read-only. You need the state to answer the query, but you don't need the invariant enforcement because you aren't changing anything.
Another case is when you need state from another aggregate to process a command properly, but small latency in the data is an acceptable risk to the data. In that case, you query the "other" aggregate to get state. If you were to run that query within the domain model itself, the right way to do so would be via a domain service.
In most cases, though, you'll be equally well served to run the query when generating the command (ie, in the client), or when handling the command (in the application, outside the domain). It would be very unusual for a business to consider domain service latency to be acceptable but client latency to be unacceptable.
(Disconnected clients are one case where that can be especially problematic; when the command is generated and then queued for a long period of time before being dispatched to the server).
DDD teaches us to build our classes like their real-world prototypes.
So instead of using setters
job = new Job
job.person = person
job.since = time.Now()
job.title = title
we define well-named methods in our aggregation root
job = person.promote(title, /** since=time.Now() **/)
Now the tricky part
Assume we have an UI for an HR where he/she enters a new title via the HTML form and makes a typo like "prgrammer" (Of course in real application there'd be a select list, but here we have a text input), or selects a wrong date (like default today)
Now we have a problem. There are no typos in real world. Our John Doe is definitely a "programmer" and never a "prgrammer"
How do we fix this typo in our domain model?
Our Person has just promote, demote, fire, etc. methods, which reflect the HR domain model.
We could cheat a little bit and change the Job record directly, but now we have a Job.setTitle method, that doesn't reflect our domain model and also, setters are evil, you know.
That may look a little "academic", but that really bugs me when I try to build a good domain model for a complex application
Another side of DDD is invariants - "always valid" entity. And when you try to break this invariant (some rule) you must stop execution and say "loudly" adout this (throw exception). So, you need to have a list of valid titles and when you try to change title (does not matter how) to invalid state, you must throw some usefull exception.
To "fix" typo situations you must separate operations in your domain promote is one operation (it may check something, sent contratulation email :) and so on). And edit operation - just to edit some properties. So, the differenece is in logic of operations. You can't call promote without some preconditions (for example, required experience of worker), but you can call edit and fix worker's name because of type.
And usually this operations are separated between different users: only HR's can promote but a worker can edit his name, if it's wrong.
This solution is very complicated for such example, but it's always with DDD.
The main concept - separate operations. Each one with their own conditions, permissions, rules.
A question about invariants (rules).
If a client is purely entering data, then the underlying domain in this (bounded) context is not very deep. In these cases, it's fine to use a CRUD style application and allow titles to be changed (setTitle()).
Just make sure dependent BCs (e.g., billing, vacation planning, ...) where no such thing as "invalid data" exists, can react to changes in your CRUD context appropriately.
The application should enforce input correctness before it reaches the domain layer, no garbage input. If that means using a dropdown for the job titles then so be it. You can validate the title against existing titles.
In my company of 18 thousand employees, typo happens all the time. You are going to have to be pragmatic about this and accept that there will be setters in your code (one way or another)
Pragmatic thinking is very much at the core of the domain driven design, and is what keep things simple.
"Purity is good in theory, but in practice it can be very difficult to achieve, and sometimes you must choose the pragmatic approach" - Patterns, Principles, and Practices of Domain-Driven Design (2015)
"There are no typos in real world", I get what you mean, but that's not true, there are human mistakes in real world scenarios and they should be accounted for in your domain if they are frequent.
If data entry errors aren't frequent it may not be worth the extra modeling efforts and those could perhaps just get fixed directly in the DB. It also depends if the business wishes to learn something about those mistakes or not.
However, if data entry errors are frequent, it might be an indicator that the system is perhaps not offering enough guidance and the business may wish to learn more about those errors in order to make processes more efficient and less error-prone.
You may wish to implement an operation such as job.correctTitle(...), perhaps in a BC dedicated to data corrections? Also, it's probably very rare that each and every piece of information will be erroneous so corrective operations can be segregated. That means you probably do not need a job.correctAllInformation(...) kind of operation.
This whole scenario is very fictive since job titles would usually be managed in a separate BC from where they are used and they would probably get picked from a list, therefore typos would be less frequent, but you will always have to deal with data entry errors. Choosing the appropriate solution is not always easy and will vary from case to case, but try to stay pragmatic and not strive for the perfect model in every sphere of your domain.