My CQRS application has some complex domain objects. When they are created, all properties of the entity are directly specified by the user, so the
CreateFooCommand has about 15 properties.
FooCreatedEvent thus also has 15 properties, because I need all entity properties on the read-side.
As the command parameters must be dispatched to the domain object and FooCreatedCommand should not be passed to the domain,
there is a manual mapping from CreateFooCommand to the domain.
As the domain should create the domain event,
That is another mapping from the domain Foo properties to FooCreatedEvent.
On the read side, I use a DTO to represent the structure of Foo as it is stored within my read-model.
So the event handler updating read-side introduces another mapping from event parameters to DTO.
To implement a simple business case, we have
Two redundant classes
Three mappings of basically the same properties
I thought about getting rid of command/event arguments and push the DTO object around, but that would imply that the domain can receive or create a DTO and assign it to the event.
Sequence:
REST Controller --Command+DTO--> Command Handler --DTO--> Domain --(Event+DTO)--> Event Handler
Any ideas about making CQRS less implementation pain?
I see the following options:
Create a immutable DTO class FooDetails that is used by both CreateFooCommand and FooCreatedEvent by injecting it in the constructor; type hint the aggregate method against FooDetails; for example new CreateFooCommand(new FooDetails(prop1, prop2, ...))
Create a immutable base class FooDetails that is inherited by both the CreateFooCommand and FooCreatedEvent and type hint the aggregate method against FooDetails
Completely change style and use the style promoted by cqrs.nu in which commands are sent directly to the aggregates; the aggregates have command methods like FooAggregate::handle(CreateFooCommand command); I personally use this style a lot.
With CQRS + ES you opted for a more complex approach with more moving parts, knowing that it would allow you to achieve more. Live with it. The strength of this approach implies separating concerns. A Command is a command, an Event is an event, etc. Although many of them may look similar along the chain, there might be exceptions. Some may contain additional data, or slightly different aspects of the same data. A Command can have meta information about the applicative context (who initiated the command, when, is it a retry, etc.) that doesn't concern the Domain. Read models will often include information about related objects to be displayed in addition to their own info (think parent-child relationship).
There's only so much of the seemingly similar code you can cut off before you block yourself from modelling these exceptions. And introducing inheritance or composition between these data structures is often more complex than the original pain of having to write boilerplate mapping code.
Related
I have a question about keeping track of objects in different layers of a software application. In my application, I have objects in the domain layer (e.g. LineShape) that are used to represent business entities, and I have corresponding objects in the presentation layer (e.g. System.Windows.Shapes.Line) that are used to display these entities on the screen.
My question is, how do I keep the correspondence between the domain objects and the presentation objects, so that I can identify which domain object is represented by a given presentation object?
For example, if the user clicks on a System.Windows.Shapes.Line in the user interface, how can I determine which LineShape in the domain layer this object represents?
I have thought of a few potential solutions, but none of them seem ideal, especially for larger and more complex object models.
One solution is to use a dictionary that maps presentation objects to domain objects. In this case, when the user clicks on a System.Windows.Shapes.Line, I could look up the corresponding LineShape in the dictionary.
Another solution is to use an ID for both the presentation and domain objects. This approach has the advantage of being simple, but it seems strange to me to use IDs for every object in a domain-driven design, as IDs are typically used only for entities.
Are there any best practices or established patterns for solving this problem?
Use an Id for objects both in Presentations and Domain. This sounds a
bit strange to me, because as far as I am aware, we are not supposed
to use Id for every object in DDD, just for entities.
Perhaps you would be looking at an address rather than an ID. Even values must somehow be addressed so they can be replaced. Such an address may be a class property's name, an array's index, etc.
If you see the whole drawing as a collection of shape values then you could always use the shape's index as the address allowing to replace that specific shape value in the collection.
However, note that the address is only valid as long as you are working against the expected drawing's version.
Furthermore, you could also use the combination of all shape's properties to identify a given shape to modify. If you have two identical shapes (same shape, position, layer, etc.), does it matter which one you re-shape? The final drawing would look exactly the same.
In the end if it makes your life easier to model shapes as entities and given them an ID then perhaps that's the right model too even though you may not care about the specific shape's entire lifecycle.
Finally, note that if shapes are values then you can't possibly keep a reference to them in view models since values are immutable. Also, if shapes are entities, but the drawing is the Aggregate Root then shape entities shouldn't be accessible outside the root. Therefore it most likely only makes sense to reference a domain's Shape in the view model if it's an AR (unless you violate the visibility rule, but still enforce invariants through root-handled events). Also note that address/ID references may be the only option if your domain model lives on another tier.
You've asked a somewhat broad question, so I will give what I think is a correct but general answer.
In WPF, one way or another, the on-screen controls will have a DataContext. The DataContext generally speaking should be the object you want to get a hold of.
This should be the case more or less regardless of what method you use to populate all the screen controls.
It may suit your program to create special viewmodel classes which bridge between your "native" data objects, in which case those viewmodel classes will be set as the DataContext objects. If you don't need the viewmodel then the native data objects will play that role.
If you are using events, then in the code-behind for the event you can directly access the DataContext property, cast it to the expected type, and off you go.
If you are using commands then generally they are part of the viewmodel object in the first place, so they can just act directly on the object which owns them.
Does it make sense to create commands that just hold objects? For example:
public class CreateCommand : IRequest
{
SomeDTO SomeDTO { get; set; }
}
public class UpdateCommand : IRequest
{
SomeDTO SomeDTO { get; set; }
}
Or perhaps something like this (deriving):
public class UpdateCommand : SomeDTO, IRequest
{
}
Or commands/requests should be treated as DTOs themselves? I'm confused because I saw many ways of doing things. Also copying all properties to command/request classes doesn't sound like a nice thing to do.
How do you do this in your projects?
Do you map your commands directly to your domain models or you use commands just to pass DTOs?
In case of using MVC framework what should be the input of my controller actions? Should it be a command, or should I create command inside my action implementation and send it? (I guess that will depend on how I model my commands)
Does it make sense to create commands that just hold objects?
No, there is no value added to the extra class: no semantics, no behavior...
Or commands/requests should be treated as DTOs themselves?
Commands (in the CQRS sense of the term) are DTO's by nature. They are dumb data bags that circulate between layers/tiers.
Do you map your commands directly to your domain models
It depends if you favor a task-based UI over a CRUD-based UI. If you do DDD/rich domain model - some would even say basic OO encapsulation - you wouldn't map them. Command names would maybe match entity methods, but their contents are not automatically mapped to domain model fields.
In case of using MVC framework what should be the input of my
controller actions? Should it be a command, or should I create command
inside my action implementation and send it?
I would say both are legit and applicable, except the occasional technical quirk with MVC model binding.
Commands and domain objects, at least in my world, have different design constraints. In particular, commands are part of the API surface - they are part of the contract with other services - and therefore need to have compatible definitions over long periods of time. Domain objects, on the other hand, are local to our current way of doing things - they are part of our organization of data within the black box. So we can change those at any cadence we like.
Commands that cross process boundaries are messages, which is to say byte[]s. That's the bit that needs to be stable, both in form and semantics.
byte[] is domain agnostic, and it's fairly common to pass through several other domain agnostic intermediate stages in "parsing" the message
byte[] -> utf8
utf8 -> DOM
DOM -> Dictionary
...
but we're generally driving toward a domain specific expression of the contract.
See, for instance Mark Seemann
At the boundaries, applications are not object-oriented.
A DTO is a representation of such a piece of data mapped into an object-oriented language.
Having coerced the byte[] into a form that is convenient for querying, then we can start thinking about whether or not we want to use that data to start initializing "objects".
The other question that you may be asking - is there value in a having the message data within a generic metadata "envelope". That kind of pattern occurs all the time - the most familiar example being that an HTTP POST is a bunch of generic headers attached to a message-body.
The data and the metadata are certainly separate concerns; it definitely makes sense to keep them distinct in your solution.
I think compositing the data structures, rather than inheriting them, is going to be the more maintainable option.
public class Envelope<Message> ....
might be a reasonable starting point.
You should treat the command as a "verbal sentence" instructing your domain to do something. For example the "UpdateCommand" instructs your domain to update something. Inside the command you should include the specifics of the command (in your case that dto is fine)...
However be very carefull with those DTO's. You do not want your domain to be dependent on MVC but the other way around. Be sure that the assembly where the dto is living is not of a higher (in the direction of MVC) level than the domain logic.
In your MVC you should have only:
Dependency injection setup
Controllers & Views
Controllers should only contain the code required to transform from the method (http) parameters (witch are unsecure) to the dto required by the domain, and calling the domain.
At least that is the way I'm doing it.
In my domain each Domain Entity may have many Value Objects. I have created value objects to represent money, weight, count, length, volume, percentage, etc.
Each of these value objects contains both a numeric value and a unit of measure. E.g. money contains the monetary value and the currency ($, euro,...) , weight contains the numeric value and the unit of weight (kilo, pound, ...)
In the user interface these are displayed side-by-side as well: field name, its value followed by its accompanying unit, typically in a properties panel. The domain entities have equivalent DTOs that are exposed to the UI.
I have been searching for the best way to transfer the value objects inside the DTOs to the UI.
Do I simply expose the specific value object as a part of the DTO?
Do I expose a generic "value object"-equivalent that provides name/value/unit in a DTO?
Do I split it into separate name/value/unit members inside the DTO, just to reassemble them in the UI?
Do I transfer them as a KeyValuePair or Tuple inside the DTO?
Something else?
I have searched intensively but no other question seems to quite address this issue. Greatly appreciate any suggestions!
EDIT:
In the UI both values and units could get changed and sent back to the domain to update.
I would be inclined to agree with debuggr's comment above if these are one-way transfers; Value Objects aren't really Domain objects - they have no behaviour that can change their state and therefore in many ways they are only specialised "bit-buckets" in that you can serialise them without losing context.
However; if you have followed DDD practices (or if your back-end is using multi-threading, etc) then your Value Objects are immutable i.e they perhaps look something like this:
public class Money
{
readonly decimal _amount;
readonly string _currency;
public decimal Amount {get{return _amount;}}
public decimal Currency {get{return _currency;}}
public Money(decimal amount, string currency)
{
//validity checks here and then
_amount=amount;
_currency=currency;
}
}
Now if you need to send these back from the client, you can't easily re-use them directly in DTO objects unless whatever DTO mapping system you have (custom WebAPI Model binder, Automapper, etc) can easily let you bind the DTO to a Value Object using constructors...which may or may not be a problem for you, it could get messy :)
I would tend to stay away from "generic" DTO objects for things like this though, bear in mind that on the UI you still want some semblance of the "Domain" for the client-side code to work with (regardless of if that's Javascript on a Web Page or C# on a Form/Console, or whatever). Plus, it tends to be only a matter of time before you find an exceptional Value Object that has Name/Value/Unit/Plus One Weird Property specific to that Value concept
The only "fool-proof"*** way of handling this is one DTO per Value Object; although this is extra work you can't really go wrong - if you have lots and lots of these Value Objects, you can always write a simple DTO generation tool or use a T4 template to generate them for you, based on the public properties of your Value Objects.
***not a guarantee
DDD is all about behavior and explicitly expressing intent, next to clearly identifying the bounded contexts (transactional and organizational boundaries) for the problem you are trying to solve. This is far more important than the type of "structural" questions for which you are requesting answers.
I.e. starting from the "Domain Entities" that may have "Value Objects", where "Domain Entities" are mapped as a "DTO" to show/be edited in a UI is a statement about how you have structured things, that says nothing about what a user is trying to achieve in this UI, nor what the organization is required to do in response to this (i.e. the real business rules, such as awarding discounts, changing a shipping address, recommending other products a user might be interested in, changing a billing currency, etc).
It appears from your description, that you have a domain model that is mirroring what needs to be viewed/edited on a UI. That is kinda "putting the horse behind the carriage". Now you have a lot of "tiers" that provide no added value, and add a lot of complexity.
Let me try to explain what I mean, using the (simplified) example that was mentioned on having an "Order" with "Money". Using the approach that was mentioned, trying to show this on screen would likely involve the following steps:
Read the "Order Entity" for a given OrderId and its related "Money" values (likely in Order Lines for specific Product Types with a given Quantity and Unit Price). This would require a SQL statement with several joins (if using a SQL DB).
Map each of these somehow to a mirroring "domain objects" structure.
Map these again to mirroring a "DTO" object hierarchy.
Map these "DTO" objects to "View" or "ViewModel" objects in the UI.
That is a lot of work that in this example has not yielded any benefit of having a model which is supposed to capture and execute business logic.
Now as the next step, the user is editing fields in a UI. And you somehow have to marshal this back to your domain entity using the reverse route and try to infer the user's intent from the fields that were changed and subsequently apply business rules to that.
So say for instance that the user changes the currency on the "MoneyDTO" of a line item. What could be the user's intent? Make this the new Billing Currency and change it for all other line items as well? And how does this relate to the business rules? Do you need to look up the exchange rate and change the "Moneys" for all line items? Is there different business logic for more volatile currencies? Do you need to switch to new rules regarding VAT?
Those are the types of questions that seem to be more relevant for your domain, and would likely lead to a structure of domain entities and services that is different from the model which is viewed/modified on a UI.
Why not simply store the viewmodel in your database (e.g. as Json so it can be retrieved with a single query and rendered directly), so that you do not need additional translation layers to show it to a user. Also, why not structure your UI to reveal intent, and map this to commands to be sent to your domain service. E.g. a "change shipping address" command is likely relevant in the "shipping" bounded context of your organisation, "change billing currency" is relevant in the "billing" bounded context.
Also, if you complement this with domain events that are generated from your domain, denoting something that "has happened" you get additional benefits. For example the "order line added" event could be picked up by the "Additional Products A User Might Be Interested In" service, that in response updates the "Suggested Products" viewmodel in the UI for the user.
I would recommend you to have a look at concepts from CQRS as one possible means for dealing with these types of problems. As a very basic introduction with some more detailed references you could check out Martin Fowler's take on this: http://martinfowler.com/bliki/CQRS.html
Im thinking about the design of entity baseclasses for a larger application and would like some opinions. Primarily if what specified is the way it has to be done or if there are a cleaner way.
In the solution i have some baseclass variants which all entities will inherit. The relations can be specified as below:
EntityBase//the primary baseclass containing name and id + other stuff
NestedEntityBase:EntityBase //(if class will be able to contain lists of itself)
VersionedEntityBase:EntityBase //(Some parameters specific for versioned entities)
VersionNestedEntityBase:NestedEntityBase// (versioned AND nested)
CurrentStateEntityBase:VersionedEntityBase// (the currentstate objects)
VersionStateEntityBase:VersionedEntityBase// (old objects, saved when surrentstate objects change)
CurrentStateNestedEntityBase:VersionNestedEntityBase// (the currentstate objects)
VersionStateNestedEntityBase:VersionNestedEntityBase //(old objects, saved when surrentstate objects change)
This unfortunately creates some code duplication since multiple inheritance isnt possible.
It will also set the divisions for the generic services and generic controller baseclasses.
Is this how it must be handled or am i missing some clever way of doing this more effectively?
How about Decorator design pattern: http://en.wikipedia.org/wiki/Decorator_pattern
It allows to extend class hierarchy with some new behaviour without duplicating
this whole hierarchy every time. Also it adds benefit of extending behaviour in
runtime (not only at compile time).
I'm looking for a good way to add arbitrary properties to the objects in a strongly typed list, based on the principle that I shouldn't pass a DataTable from my business layer to my presentation layer.
For example, I might have a Category class with the properties CategoryId and Title. On one page I would like to fetch a list of all categories (ie. List<Category>) together with the most expensive product in each category.
A while ago, I would have just returned a DataTable with some additional columns in it with the product data in, but I'm trying not to do that -- it would be trivial to set up it's not good practice.
One option is to add a MostExpensiveProduct property to my Category class, but I might want to display the most recently added product in another case, or the cheapest product, so I'd end up adding a lot of properties to cover all the options. This just doesn't feel right to me.
Am I missing a trick here? What is the best way of doing this? Or should I just be returning a DataTable to which I can add as many columns as I need and not worry about it?
The issue seems to be you have a lot of different views you'd like to offer the user. The options I see are:
You could construct separate classes for each view that inherit from the Category class. Code gen would be a good solution here.
You could store an Attributes property, which has an IDictionary interface, and refer to items by key. I'm becoming a fan of this approach.
You could generate a data table only for binding purposes, for these views... or develop a data table like component where you can refer to fields by Key...
For fields that you compute (say you store sales tax and net price, and compute gross cost), you could store as a method of the Category object, or as an extension method.
I'm sure there are other options that I haven't thought about...
HTH.
You should create a specialized class (a view model) for each view you have containing only the properties you are interested in using in the view. This may seem like unnecessary duplication for the simplest cases, but pays off in terms of consistency and separation of layers. You can construct the view models manually, or if that gets tedious, use an object-object mapping framework like AutoMapper.
There are several things to consider here IMHO. First, it seems that the only reference from Category to Product should be Category.Products, meaning you should never have something like Category.MostExpensiveProdcut etc. As far as your business layer, I would do something like this:
From your code behind in the presentation layer:
call CategoryManager.GetCategories();
call List<Product>ProductManager.GetMostExpensiveProducts(List<Category>);
Now that you have a list of Categories, and a list of Products (assuming your Product has a reference back to its Category) you have all the necessary information to work with. Using this setup your entities (Category, Product) are not polluted.
Another thing to consider is introducing a services layer. If you find that you don't want (for whatever reason) to make two calls to the business managers, rather you want to make a single call and get all your information in one shot I would consider introducing a services layer sometimes aka "application facade". This facade would be responsible for making the individual calls to the business managers and combining results into one response before shipping it back to the UI layer. Someone mentioned that that custom object would be a "ViewModel", which is correct but often used in reference to MVC. Another name for it would be a DTO (Data Transfer Object), which designed for use with service layers/application facade.