What are the differences between the Command Dispatcher and Mediator Design Pattern? - cqrs

Recently I've been introduced to the Command Dispatcher Pattern which could help the commands to be decoupled from the command handlers in our project that's based on the Domain-Driven Design approach and CQRS pattern.
Anyway, I'm confused it with the Mediator design pattern.
Robert Harvey has already answered a question about the Command Dispatcher pattern as following:
A Command Dispatcher is an object that links the Action-Request with
the appropriate Action-Handler. It's purpose is to decouple the
command operation from the sending and receiving objects so that
neither has knowledge of the other.
According to the Wikipedia, The mediator pattern is described as:
With the mediator pattern, communication between objects is
encapsulated within a mediator object. Objects no longer communicate
directly with each other, but instead communicate through the
mediator. This reduces the dependencies between communicating objects,
thereby reducing coupling.
So, as my understanding both of them are separating the command form the commander which allow us to decouple from the caller.
I've seen some projects on Github that are using the Command Dispatcher Pattern to invoke the desired handler for the requested command while the other ones are using mediator pattern to dispatch the messages. (E.g. in most of the DotNet projects, the MediatR library is used to satisfy that).
However, I'd like to know what are the differences and benefits of using one pattern than another in our project that is based on the DDD approach and CQRS pattern?

The Command Dispatcher and Mediator patterns (as well as the Event Aggregator Pattern) share similarities in that they introduce a mediating component to decouple direct communication between components. While each can be used to achieve use cases for which the other pattern was conceived, they are each concrete patterns which differ in their original targeted problems as well as the level to which they are suited for each need.
The Command Dispatcher Pattern is primarily a convention-over-configuration approach typically used for facilitating UI layer calls into an Application Layer using discrete types to handle commands and queries as opposed to a more traditional Application Service design. When representing the queries and commands that might typically be represented in a course-grained service (e.g. OrderService) as discrete components (e.g. CreateOrderCommand, GetOrderQuery, etc.), this can result in quite a bit of noise in UI-level components such as ASP.Net MVC Controllers where a constructor might otherwise need to inject a series of discrete interfaces, only one of which would typically be needed for each user request (e.g. Controller Action). Introducing a dispatcher greatly reduces the amount of code needed in implementing components such as ASP.Net MVC Controllers since the only dependency that need be injected is the dispatcher. While not necessarily a primary motivation of the pattern, it also introduces the ability to uniformly apply other patterns such as Pipes and Filters, and provides a seam where command handler implementations can be determined at run time. The MediatR library is actually an implementation of this pattern.
The Mediator Pattern concerns the creation of mediating components which encapsulate domain-specific orchestration logic that would otherwise require coupling between components. That is to say, the mediating component in this case isn't just a dumb dispatcher ("Hey, anybody know how to handle an XYZRequest?"), but is purpose-built to follow a specific set of operations that need to occur when a given operation happens, potentially across multiple components. The example given in the GoF Design Patterns book is a UI component with many interconnected elements such that changes to one need to effect changes to a number of other components and vice-versa (e.g. typing into a text field causes changes to a drop-down and multiple check boxes and radio buttons, while selecting entries within the dropdown effect changes to what's in the text field, check boxes, and radio buttons, etc.). With the provided solution, a mediating component contains logic to know exactly which components need to get updated, and how, when each of the other components change.
So, the Mediator Pattern would be used when you need a component custom-built to facilitate how a number of other components interact where normal coupling would otherwise negatively affect maintainability whereas the Command Dispatcher Pattern is simply used as a dumb function router to decouple the caller from the called function.

Mediator pattern is more low level and generic in its pure concept. Mediator pattern does not define the kind of communication or the kind of message you use. In Command Dispatcher you are in a upper layer (contextually and conceptually) in which the kind of communication and message is already defined.
You should be able to implement a Command Dispatcher patter with a Mediator pattern (ergo with MediatR) as foundation.

Related

.Net Core Rest API Best practise

I was wondering what the best practise would be concerning the following API structure:
OrderItemDepartment has a one to many relationship with OrderItemSection which in turn has a one to many relationship with OrderItem.
Dividing the api into controllers with each having CRUD actions e.g.:
OrderItemDepartmentsController
Get: OrderItemDepartments.
OrderItemSectionsController
Get: OrderItemSections.
OrderItemsController
Get: OrderItems.
..Or having a single controller serving the OrderItems, Departments and Sections via routing:
OrderItemsController
Get: OrderItems/Departments
Get: OrderItems/Sections
Get: OrderItems*
I doubt there's a single clear answer for this that will cover all cases, but in general it's a good idea to encapsulate responsibility an logic for each specific part of your application within it's own class.
You mention CRUD (Create, Read, Update, Delete), and that is a central point here; As the name sugests, these operations typically follow a certain pattern. If you are able t organize all of your contoller-classes in a similar way, you may be able to extract common logic from them, either into helper-classes or into interfaces that each controller can implement. This will in turn make your application more flexible and less messy if (when?) you have to expand it at a later time.
Using separate controllers in the top level of your app is also likely to make it easier to organize lower-level components. For example, you might have separate business- and / or repository-components corresponding to each controller, and yet each of these components may implement common interfaces. That way, each part of your application will consist of a separate but internally consistent "vertical slice" (e.g. controller, Business and Repository).
Now if you need to add new functionality to your application, you have a clear pattern which will be easy to understand, and speed up development: Add a Controller that implements the same common interfaces as those you already have, and do the same for new components in your business- and repository-layers, respectively.

Is it possible to do DDD and REST interface and language mapping?

REST has a uniform interface constraint which is the following in a very zipped opinion based format.
You have to use standards like HTTP, URI, MIME, etc...
You have to use hyperlinks.
You have to use RDF vocabs to annotate data and hyperlinks with semantics.
You do all of these to decouple the client from the implementation details of the service.
DDD with CQRS (or without it) is very similar as far as I understand.
By CQRS you define an interface to interact with the domain model. This interface consists of commands an queries classes.
By DDD you define domain events to decouple the domain model from the persistence details.
By DDD you have one ubiquitous language per bounded context which expresses the semantics.
You do all of these to completely decouple the domain model from the outside world.
Is it possible to map the REST uniform interface to the domain interface defined by commands and queries and domain events? (So the REST service code would be generated automatically.)
Is it possible to map the linked data semantics to the ubiquitous languages? (So you wouldn't need to define very similar terms, just find and reuse existing vocabs.)
Please add a very simple mapping example to your answer, why yes or why not!
I don't think this is possible. There is a term which I believe describes this problem, it is called ontology alignment.
In this case have have at least 3 ontologies:
the ubiquitous language (UL) of the domain model
the application specific vocab (ASO) of the REST service
the linked open data vocabs (LODO) which the application specific vocab uses
So we have at least 2 alignments:
the UL : ASO alignment
the ASO : LODO alignment
Our problem is related to the UL : ASO alignment, so let's talk about these ontologies.
The UL is object oriented, because we are talking about DDD and domain model. So most of the domain objects entities, value objects are real objects and not data structures. The non-object-oriented part of it are the DTOs like command+domainEvent, query+result and error on the interface of the domain model.
In contrast the ASO is strictly procedural, we manipulate the resources (data structures) using a set of standard methods (procedures) on them.
So from my aspect we are talking about 2 very different things and we got the following options:
make the ASO more object oriented -> RPC
make the UL less object oriented -> anaemic domain model
So from my point of view we can do the following things:
we can automatically map entities to resources and commands to operations by CRUD, for example the HydraBundle does this with active records (we can do just the same with DDD and without CQRS)
we can manually map commands to operations by a complex domain model
the operation POST transaction {...} can result a SendMoneyCommand{...}
the operation GET orders/123/total can result a OrderTotalQuery{...}
we cannot map entities to resources by a complex domain model, because we have to define new resources to describe a new service or a new entity method, for example
the operation POST transaction {...} can result account.sendMoney(anotherAccount, ...)
the operation GET orders/123/total can result in an SQL query on a read database without ever touching a single entity
I think it is not possible to do this kind of ontology alignment between DDD+CQRS and REST, but I am not an expert of this topic. What I think we can do is creating an application specific vocab with resource classes, properties and operations and map the operations to the commands/queries and the properties to the command/query properties.
You have posed some interesting questions here.
To start with I do not quite agree with
By DDD you define domain events to decouple the domain model from the
persistence details.
I think you might be confusing Event Sourcing ES with DDD, ES can be used with DDD but its very much optional in fact you should give it a lot of thought before choosing it as your persistence mechanism.
Now to the bulk of your question, of whether REST and DDD get along if yes how ?
My take on it, yes they do get along, however generally you do not want to expose your domain model via a REST interface, you want to build a abstraction over it and then expose that.
You can refer to this answer here, for a little more detail.
However i cannot recommend enough the Implementing Domain-Driven Design book, Chapter 14 Application deals with your concern to a fair degree.
I could not have explained it more thoroughly than the book and hence referring you there :)

Functional programming equivalents for the following [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I am trying to make the leap from functional programs for "hello world" equivalents to more real-world applications.
As I come from a Java world and have been exposed to all it's design patterns, my modeling process is still very Java oriented (e.g. I think in terms of *Managers, *Factory, *ClientFactory, *Handler etc.)
Changing my thought process in one shot, will be hard so I was hoping to get some pointers on how the following scenarios (described in a OO way) would be modeled in a functional language.
Examples in a functional language like Clojure/Haskell (or perhaps a hybrid like Scala) would be helpful.
Stateless Request handlers
E.g. is a Servlet. It is essentially a request handler with methods like doGet, doPost. How would one model such a class in a functional language?
Orchestrator classes
Such classes don't do anything by themselves, but just orchestrate the whole process or workflow. They offer multiple entry point APIs.
E.g. A OrderOrchestrator orchestrates a multiple step workflow starting with payment instrument validation, shopping cart management, payment, shipment initiation etc.
They might maintain some internal state of their own that is used by the different steps like payment, shipment etc.
ClientFactory pattern
Let's say you have written a client that for a LogService that is used by your client to log traffic data about their services. The client logs the data in S3 under buckets and accounts managed by you and you provide additional services like reporting and analytics on this data.
You don't want your customer to worry about providing the configuration information like AWS account info etc and hence you provide a ClientFactory that instantiates the appropriate client object based on whether this is for testing or production purposes without requiring the customer to provide any configuration. E.g. LogServiceClientFactory.getProdInstance() or LogServiceClientFactory.getTestInstance().
How is such a client modeled in a functional language?
Builder Pattern and other Fluent API designs
Client libraries often provide Builders to create objects with complex configuration. Sometimes APIs are also fluent to make it easy to create. An example of Fluent API is Mockito APIs : Mockito.when(A.get()).thenReturn(a) IIRC this is internally implemented by returning progressively restrictive Builders to allow the developer to write this code.
Is this a parallel to this in the functional programming world?
Datastore instances
Let's say that your codebase uses data stored in a ActiveUserRegistry from multiple places. You want only 1 instance of this registry to exist and have the entire code base access this registry. So you provide a ActiveUserRegistry.getInstance() that guarantees that all the code base accesses the instance (Assume that the instance is thread-safe etc.)
How is this managed in a functional setting? Do we have to make sure the same instance is passed around in the entire codebase?
Below is something to get started:
Stateless Request handlers
Clojure: Protocols
Haskell: Type classes
Orchestrator classes
State monad
ClientFactory pattern
LogServiceClientFactory is a Module and getProdInstance and getTestInstance being the functions in the module.
Builder Pattern and other Fluent API designs
Function composition
Datastore instances
Clojure: Function that uses an atom (to store and use the single instance)
Haskell: TVar,MVar
I'm not vary familiar with the many of these Java-style structures, but I'll take a stab at answering:
Stateless Request handlers
These exist in the functional world as well. Functions can fill this role easily, even with something as simple as a function from requests to responses. The Play Framework uses something more powerful, specifically a function from the Request to an Iteratee (type (RequestHeader) ⇒ Iteratee[Array[Byte], SimpleResult]). The Iteratee is an entity that can progressively consume input (Array[Byte]) as it is received and eventually produce the response (SimpleResult) to give back to the client. The request handler function is stateless and can be reused. The Iteratee is also stateless - the result of feeding it each chunk is actually to get a new Iteratee back, which is then fed the next chunk. (I'm oversimplifying really, it uses Futures, is entirely non-blocking, and has effective error handling - worth looking at to get a feel of the power and simplicity that functional-style code can bring to this problem).
Orchestrator classes
I'm not familiar with this pattern, so forgive me if this makes no sense. Having one giant mutable object that gets passed around is an anti-pattern. In functional code, there would be separate datatypes to represent the data that needs to passed between each stage of the process. These datatypes would be immutable.
As for things that organize other things, look at Akka and how one actor can monitor other actors underneath it, handling errors or restarting them as needed.
Builder Pattern and other Fluent API designs
Functional program has these and takes them to their logical conclusion. Functional code allows for very powerful DSLs. As for an example, check out a parser combinator library, either the one in the Scala standard library or one of the libraries for Haskell.
ClientFactory pattern and Datastore instances
I don't think this is any different in functional code. Either you have a singleton, or you do proper dependency injection. The Factory pattern is used in functional code as well, though first-class functions make many design patterns too trivial to be worth naming (from the GoF: Factory, Factory method, Command, and at least some instances of Strategy and Template can usually just be functions).
Have a look at Functional Programming Patterns in Scala and Clojure: http://pragprog.com/book/mbfpp/functional-programming-patterns-in-scala-and-clojure .
It should exactly have what you need.

Using ViewModels instead DTOs as the result of a CQRS query

Reading a SO question, I realized that my Read services could provide some smarter object like ViewModels instead plain DTOs. This makes me reconsider what information should be provided by the objects returned by the Read Services
Before, using just DTOs, my Read Service just made flat view mapping of a database query into hash like structure with minimum normalization and no behavior.
However I tend to think of a ViewModel as something "smarter" that can have generated information not provided by the database, like status icon, calculated values, reformatted values, default values, etc.
I am starting to see that the construction of some ViewModel objects might get more complicated and has potential downsides if I made my generic ReadServiceInterface return ViewModels only:
(1) Should I plan some design restriction for the ViewModels returned by my CQRS? Like making sure that their construction is almost as fast as a plain DTO?
(2) DTOs by nature are easily serialized and ready to be sent to an external system in a SOA architecture or embedded into a message. Does this mean that using ViewModels will have a negative impact on my architecture?
(3) Which type of ViewModels should I keep outside my Read Services?
(4) Should I expect all ViewModels to be retrieved from Read Services?
In the past I implemented some ViewModels that needed more than one query. In a CQRS I suppose, that is a design smell, since everything they provide, should be in only one query.
I am starting a new project, where I thought that any query will return either aggregate objects or DTOs. Since now ViewModels come into play. I am wondering:
(5) Should I plan that queries within my architecture will yield two type of objects (ViewModels+Aggregates) or three (+DTO)?
View Models (VM) serve a single master: the View. We're usually consider the VM a pretty dumb object so in this regard, there's no technical difference between a VM and a DTO, only their purpose and semantics are different.
How you build a VM is an implementation detail. Some VM are pre generated and stored in a VM repository. Others are built in real-time by a service (or a query handler) either by querying the db directly or querying other repos/services then assembling the results. There's no right or wrong and no rules about how to do it. It comes down to preference.
In CQRS the important part is separation of commands from queries i.e more than one model. There's no rule about how many queries you should do or if you should return a view model or dto. As long as you have at least one read model dedicated for queries, it's CQRS.
Don't let technicalities complicate your design. Proper design is more about high level structure and not low level implementation. Use CQRS because having a read model simplifies your app, not for other reasons. Aim for simplification and clean code, not for rigid rules that dictate a 'how to' recipe.

CQRS read model side - normalized tables

I have been reading about Command Query Responsibility Segregation (CQRS) and how this pattern would suit our current applications.
When it comes to the read model I am well aware of the concepts:
"separating read and write data model", "flat denormalized data returned by the thin read layer". In most cases we are stuck with the same database(the same read/write data model), running on SQL Server with normalized tables, with common layered application on top of it.
So, is it any value of applying CQRS on this kind of scenario?
If so, what would it be when it comes to the read model side?
Another question that hits my mind is MVC application requesting information from my thin read layer that expose flattened out views. Data exposed still need to be structured(aggragated) before presented to the user, or am I wrong?
Best regards
CQRS doesn't need to have a flattened read model; that is a benefit that CQRS can allow you to provide, but it is neither required nor a key part of the approach.
CQRS is about separation (or segregation if you follow the name). It is the Command Query Separation principle on steroid (in my opinion). The benefits that it provides you (off the top of my head) are:
separation of your read operations from your write operations;
communication between layers via messaging (e.g. commands, events), so that your layers are clean;
separation within your layers, applying the Single Responsibility Principle (e.g. your domain applies business logic, your command handles route commands, your denormalizers or event handlers (or whatever you call them) persist information to your read store, etc.)
allows you to have team members work on different parts of your application without hard dependencies between them;
etc.
So if those things above are important to you or something you want to strive for (and your application's design supports implementing CQRS), then CQRS provides benefit and value to you.
There are many benefits to CQRS. It's not the right solution for every problem, but when the stars align, it's a nice approach to your problem (even if you don't have a denormalized read store, or an event store, or an async model, etc.).
I hope this helps!
I've fought with multiple joins so many times in my career that when a structure like CQRS and ES comes along and offers a clean way to simplify the read side, I jumped at it. The nice thing is that you can get many of the benefits without necessarily implementing all the elements often associated with CQRS and ES. Just separating command from queries has the benefit of simplifying your code. However, when you do start using a de-normaliser to build out read models for you application you suddenly realise how simple, clean and performant your app can be.
If it helps to see 'how' this de-normalisation works take a look at this post (it comes with a code sample to take a gander at): How to build a master details view with CQRS and ES. I hope you find this helpful.
Applying CQRS over the same (say) third normal form database can still give you value on the read side if it allows you to stop projecting read models from domain objects.
This also allows you to better specialise your domain to (I assume) transaction processing, meaning many relationships may not be necessary.