<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Darjan Bogdan</title>
    <description>The latest articles on DEV Community by Darjan Bogdan (@darjanbogdan).</description>
    <link>https://dev.to/darjanbogdan</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F413823%2Fdc782ae4-29ba-4a5f-abcb-2994eec6bfd3.jpeg</url>
      <title>DEV Community: Darjan Bogdan</title>
      <link>https://dev.to/darjanbogdan</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/darjanbogdan"/>
    <language>en</language>
    <item>
      <title>Command &amp; Query: Domain - Validation</title>
      <dc:creator>Darjan Bogdan</dc:creator>
      <pubDate>Tue, 18 Aug 2020 06:15:47 +0000</pubDate>
      <link>https://dev.to/darjanbogdan/command-query-domain-validation-2npo</link>
      <guid>https://dev.to/darjanbogdan/command-query-domain-validation-2npo</guid>
      <description>&lt;p&gt;&lt;em&gt;The story is a part of the series about software architecture powered by command-query separation principle and aspect-oriented programming.&lt;/em&gt;&lt;/p&gt;




&lt;h2&gt;
  
  
  Data validation
&lt;/h2&gt;

&lt;p&gt;With the request handler mediator explained and implemented in the &lt;a href="https://dev.to/darjanbogdan/command-query-domain-mediator-kn7"&gt;previous&lt;/a&gt; post, all the prerequisites are in place to start building reusable generic components. Such components, that model specific cross-cutting concerns, fit nicely into the architecture this series is talking about.&lt;/p&gt;

&lt;p&gt;Even though modeling cross-cutting concerns in OO languages is challenging and may lead to tightly-coupling, the request handler &lt;a href="https://medium.com/@bogdan.darjan/command-and-query-domain-abstract-model-eca610637b28#0d21"&gt;abstraction&lt;/a&gt; provides necessary &lt;em&gt;tooling&lt;/em&gt; to make it simple and right.&lt;/p&gt;

&lt;p&gt;Implementing cross-cutting concerns using a Decorator design pattern around the generic interface &lt;code&gt;IRequestHandler&amp;lt;TRequest, TResponse&amp;gt;&lt;/code&gt; along with generic type constraints, enables non-intrusive, conditional, and dynamical addition of certain behavior to an individual handler instance. The complete solution is, reasonably, powered by a dependency injection container, which covers responsibility for the creation and management of such instances.&lt;/p&gt;

&lt;h2&gt;
  
  
  Validator — definition and model
&lt;/h2&gt;

&lt;p&gt;It’s natural to start with the data validation, as the first &lt;em&gt;concern&lt;/em&gt; to implement around the mentioned interface. Dealing with corrupt data and ensuring data input correctness is a known topic and can be achieved in many ways; starting from in-lined conditional statements to dedicated methods to specialized objects with, sometimes, complex hierarchies.&lt;/p&gt;

&lt;p&gt;In this case, the validation logic will be enclosed into an object with a single responsibility to validate data. Objects responsible for validation are going to implement a simple generic interface with a single method that takes some data as input and returns a result of the validation:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight csharp"&gt;&lt;code&gt;&lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;interface&lt;/span&gt; &lt;span class="nc"&gt;IValidator&lt;/span&gt;&lt;span class="p"&gt;&amp;lt;&lt;/span&gt;&lt;span class="k"&gt;in&lt;/span&gt; &lt;span class="n"&gt;T&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt; 
&lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="n"&gt;ValueTask&lt;/span&gt;&lt;span class="p"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;Result&lt;/span&gt;&lt;span class="p"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;bool&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&amp;gt;&lt;/span&gt; &lt;span class="nf"&gt;ValidateAsync&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;T&lt;/span&gt; &lt;span class="n"&gt;data&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;CancellationToken&lt;/span&gt; &lt;span class="n"&gt;ct&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;


&lt;p&gt;This simple abstraction covers a large variety of cases and validation needs. It has certain characteristics and design decisions worth explaining:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;No generic type constraints&lt;/strong&gt; — gives room to validate any type of data in C# (except &lt;a href="https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/unsafe-code-pointers/pointer-types"&gt;pointer types&lt;/a&gt;).&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;A contravariant generic type parameter &lt;code&gt;in T&lt;/code&gt;&lt;/strong&gt; — enables reusability if &lt;code&gt;T&lt;/code&gt; is a derived type, and there are already validators for its base (less derived) type. This is especially helpful for chaining validators in collections, such as &lt;code&gt;IEnumerable&amp;lt;IValidator&amp;lt;T&amp;gt;&amp;gt;&lt;/code&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Asynchronous method returns &lt;code&gt;ValueTask&amp;lt;T&amp;gt;&lt;/code&gt;, instead of &lt;code&gt;Task&amp;lt;T&amp;gt;&lt;/code&gt;&lt;/strong&gt; — removes &lt;a href="https://devblogs.microsoft.com/dotnet/understanding-the-whys-whats-and-whens-of-valuetask/"&gt;allocation overhead&lt;/a&gt; when an asynchronous method returns synchronously, which is often a case for data validation logic. Additionally, it removes the need to have two distinct validation methods (&lt;code&gt;Validate&lt;/code&gt; and &lt;code&gt;ValidateAsync&lt;/code&gt;) to achieve the same possibilities.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Async ceremony on the side, the validation method returns &lt;code&gt;Result&amp;lt;T&amp;gt;&lt;/code&gt; &lt;a href="https://dev.to/darjanbogdan/command-query-domain-abstract-model-662#result-definition-and-model"&gt;data structure&lt;/a&gt;&lt;/strong&gt; — provides more predictable method behavior and easier error data propagation. The method doesn’t throw an exception when validation fails, and error data is always stored in the &lt;code&gt;Error&lt;/code&gt; instance, retrievable by &lt;code&gt;Match&amp;lt;T&amp;gt;&lt;/code&gt; method.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;
  
  
  Validation decorator — model
&lt;/h2&gt;

&lt;p&gt;With the basic validator abstraction defined, it’s straightforward to implement the generic validation decorator around request handlers. It will internally use and orchestrate validators to process them in the sequence. Therefore, the order of instances in a validator collection does matter.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;em&gt;Use the dependency injection container which guarantees the order of supplied registered types in a collection of types.&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;It’s clear that the given validation interface doesn’t suit all the needs in the field, the same way the proposed decorator won’t cover all the validation scenarios some business logic or existing code could dictate. Still, the great thing about this architecture is the possibility to create different validation decorators with their own rules and behavior (e.g. concurrent processing), and easily use them side by side or even exclusively.&lt;/p&gt;

&lt;p&gt;Implementation could look something like this:&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;



&lt;p&gt;It’s important to notice how &lt;code&gt;ValidationDecorator&lt;/code&gt; has only one generic type constraint (&lt;code&gt;TRequest: IRequest&amp;lt;TResponse&amp;gt;&lt;/code&gt;) dictated by the interface it implements. When added to the &lt;a href="https://freecontent.manning.com/dependency-injection-in-net-2nd-edition-understanding-the-composition-root/"&gt;composition root&lt;/a&gt;, this kind of decorator will always be applied to any &lt;code&gt;IRequest&amp;lt;TResponse&amp;gt;&lt;/code&gt; object. Since that’s the base interface, each &lt;code&gt;TRequest&lt;/code&gt; instance sent to its handler is going to be validated by this logic.&lt;/p&gt;

&lt;p&gt;When determining how certain behavior is going to be applied, there are usually three approaches:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Required (always-on)&lt;/strong&gt;: behavior is applied to every request handled by a corresponding handler. There is no possibility to exclude a decorator dynamically. Excluding decorators from the DI composition is the only way to avoid them. No additional coding, easy to implement.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Required (opt-out)&lt;/strong&gt;: behavior is applied to every request handled by a corresponding handler. There is a possibility to exclude decorator statically or dynamically. Requires custom coding, complex to implement if seeking for an all-round good solution.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Optional (opt-in)&lt;/strong&gt;: behavior is applied only to requests which implement a specific flag interface. The interface is used as a decorator’s additional type constraint imposing a requirement for request types to fulfill in order to be processed.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Personally, I &lt;a href="https://medium.com/@bogdan.darjan/thanks-means-a-lot-8bb1f3ac9986"&gt;recommend&lt;/a&gt; the &lt;em&gt;opt-in&lt;/em&gt; approach as a rule of thumb, even if it leads to a higher number of interfaces to deal with. It’s simply easier to work with a set of behaviors and pick only the suitable ones to use for a given request. Also, the &lt;em&gt;opt-out&lt;/em&gt; approach isn’t easily implemented and may lead to the coupling or hard-coding (e.g. request type checks inside decorator to skip part of the logic). The only &lt;em&gt;always-on&lt;/em&gt; behavior which is going to be covered in the whole series is validation due to its nature. Working with a valid &lt;code&gt;request&lt;/code&gt; instance is a must, thus validation decorator is mandatory. That’s the only reason why the proposed solution doesn’t use a custom-tailored flag interface as a constraint.&lt;/p&gt;

&lt;p&gt;If that’s not preferable, a simple &lt;code&gt;IValidatedRequest&lt;/code&gt; empty flag interface can be introduced and added as a decorator’s type constraint. That enables the &lt;em&gt;opt-in&lt;/em&gt; approach for the request validation as well. Simply, a custom &lt;code&gt;TRequest&lt;/code&gt; type can optionally implement a specific interface to &lt;em&gt;activate&lt;/em&gt; a decorator that handles &lt;code&gt;IValidatedRequest&lt;/code&gt; types.&lt;/p&gt;

&lt;p&gt;Last thing worth pointing out is an &lt;a href="https://github.com/darjanbogdan/pype/blob/master/src/Pype/Results/Result.cs#L90"&gt;implicit conversion&lt;/a&gt; which makes it possible to directly return &lt;code&gt;Error&lt;/code&gt; instance instead of &lt;code&gt;Result&amp;lt;TResult&amp;gt;&lt;/code&gt;. Once the result is calculated by &lt;code&gt;ValidateAsync&lt;/code&gt; method, &lt;code&gt;error&lt;/code&gt; can be extracted using &lt;code&gt;Match&amp;lt;T&amp;gt;&lt;/code&gt; method and, finally, returned.&lt;/p&gt;

&lt;p&gt;Essentially, on top of two additional types, &lt;code&gt;ValidationDecorator&amp;lt;TRequest, TResponse&amp;gt;&lt;/code&gt; and &lt;code&gt;IValidator&amp;lt;T&amp;gt;&lt;/code&gt;, it is possible to build custom validators for any &lt;code&gt;TRequest&lt;/code&gt;. The decorator will make sure to invoke it before &lt;em&gt;execution&lt;/em&gt; reaches the handler for specific &lt;code&gt;TRequest&lt;/code&gt; — it’s that simple!&lt;/p&gt;

&lt;h2&gt;
  
  
  DataAnnotations Validator — model
&lt;/h2&gt;

&lt;p&gt;There is still a need to implement validators for each request. That can be a tedious process, especially implementing validation logic which is repeatable like &lt;em&gt;null or empty&lt;/em&gt; checks or &lt;em&gt;max length&lt;/em&gt; checks. Basically, any &lt;strong&gt;input&lt;/strong&gt; validation logic is monotonous to deal with.&lt;/p&gt;

&lt;p&gt;For that matter, &lt;em&gt;&lt;a href="https://docs.microsoft.com/en-us/dotnet/api/system.componentmodel.dataannotations?view=netcore-3.1"&gt;DataAnnotations&lt;/a&gt;&lt;/em&gt; library comes as a solution quite naturally. It’s just needed to implement a generic validator that will use &lt;em&gt;DataAnnotations&lt;/em&gt; to validate objects. Afterward, simply decorate the objects’ properties with validation attributes, and thing happens:&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;This simple example serves the purpose and is capable to validate any object (e.g. &lt;code&gt;CreateUserCommand&lt;/code&gt;) passed into it. It will either return Error with appropriate data about validation failure or true if the validation is successful. Note that nested properties validation is missing, but it can be &lt;a href="https://stackoverflow.com/a/28433753/1525637"&gt;added&lt;/a&gt; by extending base attributes from &lt;em&gt;DataAnnotations&lt;/em&gt; library.&lt;/p&gt;

&lt;h2&gt;
  
  
  FluentValidation Validator — model
&lt;/h2&gt;

&lt;p&gt;Often simple input validation isn’t enough to ensure the data correctness on a domain level. Sometimes it’s necessary to (asynchronously) fetch additional data from a remote source like a database, or validation logic is composed of smaller, more specialized components (dependencies). In such scenarios, validation via attributes is simply not powerful enough, &lt;code&gt;System.Attribute&lt;/code&gt; &lt;a href="https://docs.microsoft.com/en-us/dotnet/api/system.attribute?view=netcore-3.1#remarks"&gt;type specifics&lt;/a&gt; make it inconvenient to use in more complex cases.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;&lt;a href="https://fluentvalidation.net/"&gt;FluentValidation&lt;/a&gt;&lt;/em&gt; library is a good choice when it comes to more complex, &lt;strong&gt;domain&lt;/strong&gt; validation logic. It supports asynchronous processing, has rich feature-set and intuitive API to use.&lt;/p&gt;

&lt;p&gt;To fit it, it’s necessary to create an &lt;a href="https://en.wikipedia.org/wiki/Adapter_pattern"&gt;adapter&lt;/a&gt; which derives from the base &lt;code&gt;AbstractValidator&amp;lt;T&amp;gt;&lt;/code&gt; class and implements the new &lt;code&gt;IValidator&amp;lt;T&amp;gt;&lt;/code&gt; interface:&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;&lt;code&gt;AbstractFluentValidator&amp;lt;TRequest&amp;gt;&lt;/code&gt; is deliberately an abstract class to retain the same API interaction as the original library requires. It’s still needed to inherit the class to define validation rules inside the constructor, but the new class also makes derived validator &lt;em&gt;compatible&lt;/em&gt; with the &lt;code&gt;ValidationDecorator&lt;/code&gt;:&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;While &lt;em&gt;FluentValidation&lt;/em&gt; library offers the possibility to write a fully custom code via dedicated methods, there might be cases in which there is no need to introduce a new library (or not an option) due to the existing validators and other validation components.&lt;/p&gt;

&lt;p&gt;To reuse them along with other validators, each &lt;em&gt;legacy&lt;/em&gt; validator needs to have its own adapter that implements &lt;code&gt;IValidator&amp;lt;T&amp;gt;&lt;/code&gt; interface. Since only one method needs to be added, implementation is usually straightforward.&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;With all three validation approaches in place, the &lt;em&gt;data validation&lt;/em&gt; responsibility can be completely moved away from the central handler logic. That makes the handler clean and more readable as the validation clutter is relocated elsewhere.&lt;/p&gt;

&lt;p&gt;A higher level of encapsulation and clearer responsibility separation naturally raise performance concerns which shouldn’t be neglected. They can be tackled in many different ways; from multi-level and hybrid caching to contextual data propagation and exchange. To give an example, optimizing interaction with remote sources (database, web API, …) leveraging caching, reduces the number of expensive (slow) and volatile network roundtrips. Even if the approach can give a significant/positive impact on a general performance, it comes with &lt;a href="https://msol.io/blog/tech/youre-probably-wrong-about-caching/"&gt;the cost&lt;/a&gt; and must be carefully weighed.&lt;/p&gt;

&lt;h2&gt;
  
  
  Pipeline composition example with SimpleInjector
&lt;/h2&gt;

&lt;p&gt;The last thing to cover is the object graph composition with the help of &lt;em&gt;&lt;a href="https://simpleinjector.org/"&gt;SimpleInjector&lt;/a&gt;&lt;/em&gt; DI container. The setup shown below gives a sort of &lt;em&gt;pipeline-like&lt;/em&gt; composition in which every request goes through the validation component first, continuing as a validated request to the corresponding handler:&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;Due to &lt;em&gt;SimpleInjector’s&lt;/em&gt; powerful support for open generic types registration, it is possible to define the order of instances in a collection of types resolved by the container. In other words, &lt;code&gt;IEnumerable&amp;lt;IValidator&amp;lt;T&amp;gt;&amp;gt;&lt;/code&gt; is always resolved into collection of ordered validators which are able to handle some type T.&lt;/p&gt;

&lt;p&gt;In the case of &lt;code&gt;CreateUserCommand&lt;/code&gt;, validation will be done in the following order:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;DataValidationValidator&lt;/code&gt; — validates input data; ensures that both property values are set, &lt;code&gt;Name&lt;/code&gt; not longer than 25 characters and &lt;code&gt;Email&lt;/code&gt; valid.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;CreateUserEmailValidator&lt;/code&gt; — validates domain requirements; ensures that &lt;code&gt;Email&lt;/code&gt; is not used.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;CreateUserNameValidator&lt;/code&gt; — validates domain requirements using “&lt;em&gt;legacy”&lt;/em&gt; logic; ensures that &lt;code&gt;Name&lt;/code&gt; is allowed to use.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;In the case of another arbitrary &lt;code&gt;UpdateUserCommand&lt;/code&gt;, validation order would start with &lt;code&gt;DataValidationValidator&lt;/code&gt;, continuing with reusable and/or dedicated validators for that type in the guaranteed order as well.&lt;/p&gt;

&lt;p&gt;To conclude, with data validation components in place and flexible composition, it’s matter of creating a request and handler to handle some domain logic, possibly creating additional classes to cover specific validation behavior and run the code. There is no need to change or adapt anything else (&lt;em&gt;Open-closed principle&lt;/em&gt;), especially not composition root, which should be the ultimate goal when working with DI containers.&lt;/p&gt;

&lt;p&gt;In the next chapter, new cross-cutting concern and decorator will be covered, stay tuned to find out which one.&lt;/p&gt;




&lt;p&gt;&lt;em&gt;All the gists, examples or solutions will be done in C# using the latest .Net Core/Standard versions and hosted on &lt;a href="https://github.com/darjanbogdan?utf8=%E2%9C%93&amp;amp;tab=repositories&amp;amp;q=pype&amp;amp;type=public&amp;amp;language=c%23"&gt;Github&lt;/a&gt;.&lt;/em&gt;&lt;/p&gt;

</description>
      <category>csharp</category>
      <category>dotnet</category>
      <category>oop</category>
      <category>cqs</category>
    </item>
    <item>
      <title>Command &amp; Query: Domain - Mediator</title>
      <dc:creator>Darjan Bogdan</dc:creator>
      <pubDate>Tue, 18 Aug 2020 06:15:28 +0000</pubDate>
      <link>https://dev.to/darjanbogdan/command-query-domain-mediator-kn7</link>
      <guid>https://dev.to/darjanbogdan/command-query-domain-mediator-kn7</guid>
      <description>&lt;p&gt;&lt;em&gt;The story is a part of the series about software architecture powered by command-query separation principle and aspect-oriented programming.&lt;/em&gt;&lt;/p&gt;




&lt;h2&gt;
  
  
  Example powered by requests and handlers
&lt;/h2&gt;

&lt;p&gt;In the &lt;a href="https://dev.to/darjanbogdan/command-query-domain-abstract-model-662"&gt;preceding&lt;/a&gt; chapter, the base model, which represents commands, queries, and their handlers, was explained and implemented as an abstract model in C#. Since the model consists of essentially two interfaces, it’s possible to provide a large variety of implementations making it suitable to model many business domains.&lt;/p&gt;

&lt;p&gt;Simple user management will be taken as an example of one. Using the mentioned model as a backbone, many different actions on the &lt;em&gt;user&lt;/em&gt; object will be implemented. To keep it clean and simple, only the user’s &lt;em&gt;unique identifier&lt;/em&gt; and &lt;em&gt;name&lt;/em&gt; are properties in focus. The class itself could be easily expanded or completely changed based on the business domain’s needs.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight csharp"&gt;&lt;code&gt;&lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;User&lt;/span&gt;
&lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="n"&gt;Guid&lt;/span&gt; &lt;span class="n"&gt;Id&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="k"&gt;get&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="k"&gt;set&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;
    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="kt"&gt;string&lt;/span&gt; &lt;span class="n"&gt;Name&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="k"&gt;get&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="k"&gt;set&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;


&lt;p&gt;To implement the logic for getting a single User using its identifier, it’s necessary to implement two interfaces in separate classes. An instance of one class holds the data needed to perform a &lt;em&gt;task&lt;/em&gt;, an instance of another holds the business logic to perform a &lt;em&gt;task&lt;/em&gt;.&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;



&lt;p&gt;&lt;code&gt;GetUserQuery&lt;/code&gt; class implements &lt;code&gt;IRequest&amp;lt;User&amp;gt;&lt;/code&gt; and carries the user identifier needed to get the user successfully. &lt;code&gt;GetUserQueryHandler&lt;/code&gt; class, on the other hand, implements &lt;code&gt;IRequestHandler&amp;lt;GetUserQuery, User&amp;gt;&lt;/code&gt; interface and has a method that performs the logic to get the user from some source. Simply, the method gets &lt;code&gt;GetUserQuery&lt;/code&gt; object, passes &lt;code&gt;UserId&lt;/code&gt; to the &lt;code&gt;GetUserFromSource&lt;/code&gt; method to fetch the user and returns the retrieved &lt;code&gt;User&lt;/code&gt; object. Data fetching and materialization are not in the focus at the moment, so &lt;code&gt;GetUserFromSource&lt;/code&gt; could be virtually anything.&lt;/p&gt;

&lt;p&gt;Following the example, the other actions on &lt;code&gt;User&lt;/code&gt; object could be implemented similarly, using the same pair of generic interfaces or their derivatives such as &lt;code&gt;IRequest&lt;/code&gt; and &lt;code&gt;IRequestHandler&amp;lt;TRequest&amp;gt;&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Having all the handler implementations in place, with the help of a dependency injection container, each handler instance can be injected into another class. A typical Web API controller would look something like this:&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;What immediately comes to attention is the &lt;a href="https://blog.ploeh.dk/2018/08/27/on-constructor-over-injection/"&gt;constructor over-injection&lt;/a&gt; smell, and as such should be avoided or reduced to a minimum, especially if it would appear regularly.&lt;/p&gt;

&lt;h2&gt;
  
  
  Mediator — definition and model
&lt;/h2&gt;

&lt;p&gt;Instead of individually injecting instances of &lt;a href="https://docs.microsoft.com/en-us/dotnet/framework/reflection-and-codedom/reflection-and-generic-types#is-the-type-or-method-open-or-closed"&gt;closed&lt;/a&gt; generic interfaces, a single non-generic interface with a generic method shall be used instead. Implementation of such interface serves as a &lt;a href="https://en.wikipedia.org/wiki/Mediator_pattern"&gt;mediator&lt;/a&gt; between any &lt;em&gt;caller&lt;/em&gt; and any request handler, effectively decoupling them from each other and completely removing the initial code-smell.&lt;/p&gt;

&lt;p&gt;Although &lt;code&gt;IRequestHandlerMediator&lt;/code&gt; seems like a reasonable choice to name such interface, I prefer to use &lt;code&gt;IBus&lt;/code&gt; only because the base model can be furtherly expanded using various handler &lt;a href="https://en.wikipedia.org/wiki/Decorator_pattern"&gt;decorators&lt;/a&gt; to form a pipeline and/or in-process bus.&lt;/p&gt;

&lt;p&gt;The initial version of the interface and class implementation could look like this:&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;As mentioned earlier, Bus implementation serves as a mediator, with the responsibility to invoke &lt;code&gt;Handle&lt;/code&gt; method on a correct &lt;code&gt;handler&lt;/code&gt; instance. Handler instantiation is usually managed by a dependency injection container, so &lt;code&gt;instanceFactory&lt;/code&gt; function delegate is passed into the constructor as the only dependency of the implementation. It simply takes &lt;code&gt;Type&lt;/code&gt; argument and returns an instance of that type as an &lt;code&gt;object&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;While looking simple and straightforward, to invoke &lt;code&gt;SendAsync&lt;/code&gt; method both type parameters must be explicitly defined, which makes the usage inconvenient:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight csharp"&gt;&lt;code&gt;&lt;span class="kt"&gt;var&lt;/span&gt; &lt;span class="n"&gt;query&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nf"&gt;GetUserQuery&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
&lt;span class="kt"&gt;var&lt;/span&gt; &lt;span class="n"&gt;user&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="n"&gt;bus&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;SendAsync&lt;/span&gt;&lt;span class="p"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;GetUserQuery&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;User&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;(&lt;/span&gt;&lt;span class="n"&gt;query&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="k"&gt;default&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;


&lt;p&gt;&lt;a href="https://stackoverflow.com/questions/9764357/does-c-sharp-support-type-inference-of-the-return-type/9765156#9765156"&gt;For a reason&lt;/a&gt; C#’s type inference doesn’t take return types into account, as a matter of fact, it fails immediately per specification:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;em&gt;If the supplied number of arguments is different than the number of parameters in the method, then inference immediately fails.&lt;/em&gt; — &lt;a href="https://www.microsoft.com/en-us/download/details.aspx?id=7029"&gt;C# Language Specification&lt;/a&gt;, Version 5.0, § 7.5.2 Type Inference&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Still, explicitly defined type parameters look noisy, especially when used frequently, with long descriptive type names. Considering that both &lt;code&gt;query&lt;/code&gt; and &lt;code&gt;response&lt;/code&gt; types are known at compile-time, writing simple clean code with type safety in place should be achievable:&lt;br&gt;
&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre class="highlight csharp"&gt;&lt;code&gt;&lt;span class="kt"&gt;var&lt;/span&gt; &lt;span class="n"&gt;query&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nf"&gt;GetUserQuery&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
&lt;span class="kt"&gt;var&lt;/span&gt; &lt;span class="n"&gt;user&lt;/span&gt; &lt;span class="p"&gt;=&lt;/span&gt; &lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="n"&gt;bus&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;SendAsync&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;query&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="k"&gt;default&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;


&lt;p&gt;To make the usage more pleasant, redundant data needs to be avoided meaning the &lt;code&gt;SendAsync&lt;/code&gt; method signature needs to be adapted:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;TRequest&lt;/code&gt; type parameter removed — to match the number of method parameters and arguments&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Type of &lt;code&gt;request&lt;/code&gt; argument changed to &lt;code&gt;IRequest&amp;lt;TResponse&amp;gt;&lt;/code&gt; — to keep the same type constraint&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;With the constraints in place, implementation draft looks like the following:&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;



&lt;p&gt;Conforming to type inference rules leads to more complex implementation because the &lt;em&gt;concrete&lt;/em&gt; type of request argument is unknown at the compile time. The absence of the type makes it impossible to construct the closed generic handler type which is required to get the correct handler instance via &lt;code&gt;instanceFactory&lt;/code&gt; delegate.&lt;/p&gt;

&lt;p&gt;There are different ways to solve the problem. For example, in &lt;em&gt;MediatR&lt;/em&gt; library internal generic handler &lt;a href="https://github.com/jbogard/MediatR/tree/master/src/MediatR/Internal"&gt;wrappers&lt;/a&gt; are used to solve the same issue.&lt;/p&gt;

&lt;p&gt;In this case, only &lt;em&gt;Delegates&lt;/em&gt; and &lt;em&gt;Reflection&lt;/em&gt; are used to fill the gap. To have a reasonable solution, a few requirements and limitations must be met:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Simple enough to be easily maintainable&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Performance in-line with existing solutions to be usable&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;No &lt;code&gt;handler&lt;/code&gt; instance caching to avoid &lt;a href="https://blog.ploeh.dk/2014/06/02/captive-dependency/"&gt;captive dependencies&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;For simplicity, a naive implementation is shown, while a more comprehensive and optimized solution with safety checks and error handling in place can be found in &lt;em&gt;Pype&lt;/em&gt; &lt;a href="https://github.com/darjanbogdan/pype/blob/master/src/Pype/Bus.cs"&gt;repository&lt;/a&gt;:&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;The simplest way to solve the problem is to reintroduce the initially implemented &lt;code&gt;SendAsync&amp;lt;TRequest, TResponse&amp;gt;&lt;/code&gt; method with the small, but important difference. The type of &lt;code&gt;request&lt;/code&gt; argument is &lt;code&gt;object&lt;/code&gt;, not &lt;code&gt;TRequest&lt;/code&gt; anymore.&lt;/p&gt;

&lt;p&gt;The side-effect of casting back to &lt;code&gt;TRequest&lt;/code&gt; is neglectable to the benefits of using &lt;a href="https://blog.slaks.net/2011/06/open-delegates-vs-closed-delegates.html"&gt;closed instance delegate&lt;/a&gt; — to achieve fast and type-safe invocation via &lt;code&gt;SendAsyncDelegate&amp;lt;TResponse&amp;gt;&lt;/code&gt; delegate. It wouldn’t be possible to use it if the argument’s type remained &lt;code&gt;TRequest&lt;/code&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  Mediator — implementation benchmarking
&lt;/h2&gt;

&lt;p&gt;There are many different ways to invoke &lt;code&gt;SendAsync&amp;lt;TRequest, TResponse&amp;gt;&lt;/code&gt; function without knowing type parameters at compile time, some are:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;a href="https://docs.microsoft.com/en-us/dotnet/api/system.reflection.methodbase.invoke?view=netcore-3.1"&gt;MethodInfo.Invoke&lt;/a&gt; (&lt;a href="https://github.com/darjanbogdan/pype/blob/master/src/Pype.Benchmark/SendComparison/MethodInfoInvoke/BusMethodInfoInvoke.cs"&gt;src&lt;/a&gt;) — type unsafe method invocation via reflection&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;a href="https://docs.microsoft.com/en-us/dotnet/api/system.delegate.dynamicinvoke?view=netcore-3.1"&gt;Delegate.DynamicInvoke&lt;/a&gt; (&lt;a href="https://github.com/darjanbogdan/pype/blob/master/src/Pype.Benchmark/SendComparison/DelegateDynamicInvoke/BusDelegateDynamicInvoke.cs"&gt;src&lt;/a&gt;) — late-bound method invocation&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;a href="https://docs.microsoft.com/en-us/dotnet/api/system.dynamic?view=netcore-3.1"&gt;dynamic&lt;/a&gt; Invoke (&lt;a href="https://github.com/darjanbogdan/pype/blob/master/src/Pype.Benchmark/SendComparison/DynamicCastInvoke/BusDynamicCastInvoke.cs"&gt;src&lt;/a&gt;) — non-statically typed method invocation&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;a href="https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/delegates/"&gt;delegate&lt;/a&gt; Invoke (&lt;a href="https://github.com/darjanbogdan/pype/blob/master/src/Pype.Benchmark/SendComparison/DelegateInvoke/BusDelegateInvoke.cs"&gt;src&lt;/a&gt;) — type-safe encapsulated method invocation&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;a href="https://docs.microsoft.com/en-us/dotnet/api/system.func-3?view=netcore-3.1"&gt;Func&lt;/a&gt; Invoke (&lt;a href="https://github.com/darjanbogdan/pype/blob/master/src/Pype.Benchmark/SendComparison/FuncInvoke/BusFuncInvoke.cs"&gt;src&lt;/a&gt;) — invocation of Func delegate type&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;a href="https://docs.microsoft.com/en-us/dotnet/api/system.linq.expressions.expression.lambda?view=netcore-3.1"&gt;Expression&lt;/a&gt; Invoke (&lt;a href="https://github.com/darjanbogdan/pype/blob/master/src/Pype.Benchmark/SendComparison/ExpressionFuncInvoke/BusExpressionFuncInvoke.cs"&gt;src&lt;/a&gt;) — constructing and invoking lambda expression via expression trees&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Using dedicated delegate type (as shown in the example) which represents the reference to the &lt;code&gt;SendAsync&amp;lt;TRequest, TResponse&amp;gt;&lt;/code&gt; method is the most performant one. Based on a simple &lt;a href="https://github.com/darjanbogdan/pype/blob/master/src/Pype.Benchmark/SendComparison/SendComparisonBenchmarks.cs"&gt;benchmarking&lt;/a&gt; using dummy &lt;code&gt;PingRequest&lt;/code&gt; and &lt;code&gt;PingResponse&lt;/code&gt;:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--J9l_dkGu--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/fdmmb9kjdf49xfh8z5y5.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--J9l_dkGu--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/fdmmb9kjdf49xfh8z5y5.png" alt="Send method execution benchmarks chart"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Besides the mentioned approaches, &lt;em&gt;Generic invoke&lt;/em&gt; presents the benchmarking of the initial version — the one with inconvenient API. It serves as a reference point to evaluate whether the trade-off between performance and convenience pays off.&lt;/p&gt;

&lt;p&gt;Data sets (series) in the diagram are representing:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;&lt;em&gt;Simple&lt;/em&gt;&lt;/strong&gt; — a naive implementation for different method invocation approaches. As expected, each is slower by order of magnitude in comparison to the direct method invocation. In the case of expression trees, it’s even worse.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;&lt;em&gt;Optimized&lt;/em&gt;&lt;/strong&gt; — a reasonable implementation using caching where possible to avoid usually expensive interaction with System.Reflection namespace. The instantiation of methods, delegates, expressions or lamdas is completely mitigated by caching, invocation itself is almost the only thing that counts.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Although the best approach is still more than 2 times slower than the reference point, in absolute terms it’s only ~70ns slower which is negligible in most of the cases. Based on that and the &lt;a href="https://github.com/darjanbogdan/pype/tree/master/src/Pype.Benchmark/BusComparison"&gt;benchmarking&lt;/a&gt; comparison with the other libraries, it’s safe to conclude that this kind of solution is efficient enough to be used on a daily basis.&lt;/p&gt;

&lt;p&gt;To conclude, it’s always nice to see that extra effort to make a more convenient API paid off eventually:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Handler instances don’t have to be injected into their consumers, which makes their constructors &lt;em&gt;slim-fit&lt;/em&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Handlers are completely decoupled from each other and the rest of the system which makes it more maintainable.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Handler invocation through &lt;code&gt;IBus&lt;/code&gt; mediator comes with proper type inference support which makes the usage simple and code clean.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Finally, the fun part is reached, with the base model and mediator in place, it’s possible to expand the whole concept with many different cross-cutting aspects which will naturally fit into the whole picture. One of them, data validation, is covered in the &lt;a href="https://dev.to/darjanbogdan/command-query-domain-validation-2npo"&gt;next&lt;/a&gt; chapter.&lt;/p&gt;




&lt;p&gt;&lt;em&gt;All the gists, examples or solutions will be done in C# using the latest .Net Core/Standard versions and hosted on &lt;a href="https://github.com/darjanbogdan?utf8=%E2%9C%93&amp;amp;tab=repositories&amp;amp;q=pype&amp;amp;type=public&amp;amp;language=c%23"&gt;Github&lt;/a&gt;.&lt;/em&gt;&lt;/p&gt;

</description>
      <category>csharp</category>
      <category>dotnet</category>
      <category>oop</category>
      <category>cqs</category>
    </item>
    <item>
      <title>Command &amp; Query: Domain - Abstract Model</title>
      <dc:creator>Darjan Bogdan</dc:creator>
      <pubDate>Tue, 18 Aug 2020 06:15:01 +0000</pubDate>
      <link>https://dev.to/darjanbogdan/command-query-domain-abstract-model-662</link>
      <guid>https://dev.to/darjanbogdan/command-query-domain-abstract-model-662</guid>
      <description>&lt;p&gt;&lt;em&gt;The story is part of the series about software architecture powered by command-query separation principle and aspect-oriented programming.&lt;/em&gt;&lt;/p&gt;




&lt;h2&gt;
  
  
  Abstract model in software — where, when and why?
&lt;/h2&gt;

&lt;p&gt;Software problems which share common characteristics could be represented and associated with an abstract model, as a backbone for building generic, reusable solutions. It definitely is challenging to discover such &lt;a href="https://en.wikipedia.org/wiki/Abstraction_(computer_science)"&gt;abstractions&lt;/a&gt; as a basis to build a usable software model — it requires a lot of effort, time and experience.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;em&gt;Abstraction is the amplification of the essential and the elimination of the irrelevant.&lt;/em&gt; — Robert C. Martin, Agile Principles, Patterns, and Practices in C#&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;There are many fields in mathematics which are typically a good foundation to form an abstract model and finally build a generic solution for a particular or more general problem space. As an example, &lt;a href="https://en.wikipedia.org/wiki/Graph_theory"&gt;graph theory&lt;/a&gt; is usually the basis for any valid &lt;em&gt;graph&lt;/em&gt; representation, structure or model in software. Validity comes from the fact that theoretical definitions are embedded in abstract software models to guard a defined set of laws and provide a predictable interface to a consumer. Ultimately, a well-implemented model can serve as a generic solution for the same problems in the technical domains belonging to different business domains, such as data storage, social networking or communication networks.&lt;/p&gt;

&lt;p&gt;Another, more advanced example is the influence of the &lt;a href="https://en.wikipedia.org/wiki/Category_theory"&gt;category theory&lt;/a&gt; in functional programming. The theory itself focuses on identification and formalization of a &lt;em&gt;category&lt;/em&gt; as a mathematical structure. A &lt;em&gt;category&lt;/em&gt; is a graph which represents abstractions of other mathematical concepts and consists of &lt;em&gt;objects (nodes)&lt;/em&gt; and their &lt;em&gt;morphisms (arrows)&lt;/em&gt;. Even though the theoretical concept is quite broad and abstract, some functional programming languages, like &lt;a href="https://en.wikibooks.org/wiki/Haskell/Category_theory"&gt;Haskell&lt;/a&gt;, took advantage of such high-level abstractions, embedded their rules into core language features, and adopted terminology.&lt;/p&gt;

&lt;p&gt;How will individual abstraction be truly accomplished in the context of programming language or particular framework is solely up to abstract models’ implementation characteristics. Since source code implementation is opinionated, it’s not surprising that theoretical model realization could vary a lot. It is influenced by many things — to give a brief idea, some are:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Language paradigm — object-oriented, functional, event-driven …&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Language features — type system, generics, pattern matching …&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Framework features — concurrency, collections, garbage collection …&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Determining the right implementation direction is quite challenging, but most importantly it’s rewarding since it’ll make a certain theoretical concept easy to apply and intuitive to use in every-day development.&lt;/p&gt;

&lt;p&gt;To support the statement, a good example would be the &lt;em&gt;async/await&lt;/em&gt; feature’s advancement in C#. &lt;a href="https://en.wikipedia.org/wiki/Asynchrony_(computer_programming)"&gt;Asynchrony&lt;/a&gt;, as a theoretical concept is a well known and hot topic in computer programming. However, every language or framework which supports &lt;em&gt;async&lt;/em&gt; programming has own way of achieving it. In other words, each has a different way to implement and expose a meaningful and intuitive &lt;a href="https://en.wikipedia.org/wiki/Application_programming_interface"&gt;API&lt;/a&gt; for the developer. In fact, C#/.NET supports 3 different &lt;a href="https://docs.microsoft.com/en-us/dotnet/standard/asynchronous-programming-patterns/"&gt;approaches&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;It is known that asynchronous programming in .NET gained tremendous popularity once &lt;em&gt;async/await&lt;/em&gt; was incorporated into C#, powered by the already existing &lt;a href="https://docs.microsoft.com/en-us/dotnet/standard/parallel-programming/task-parallel-library-tpl"&gt;TPL&lt;/a&gt;. The reason is that &lt;em&gt;developers&lt;/em&gt; eventually managed to form a software model based on the complex theoretical concept, with intuitive API — to use seamlessly within the context of language and framework.&lt;/p&gt;

&lt;p&gt;Just remember how adventurous, hard to maintain and error-prone was asynchronous programming in C# without first-class compiler support, or even before, without first-class library support. Pursuing “asynchronous all the way” principle using earlier patterns (models) was much more complex and rare due to the lack of intuitive API.&lt;/p&gt;

&lt;p&gt;It’s fair to mention that such a powerful generalization comes with the &lt;a href="https://devblogs.microsoft.com/premier-developer/dissecting-the-async-methods-in-c/"&gt;cost&lt;/a&gt;, and definitely, in &lt;a href="https://en.wikipedia.org/wiki/No_Silver_Bullet"&gt;essentially&lt;/a&gt; complex domains it might be needed to “fallback” to the lower-level models which usually expose a certain degree of implementation details to expose necessary extensibility and configurability (e.g. &lt;code&gt;TaskFactory.StartNew&lt;/code&gt;, &lt;code&gt;Task.Run&lt;/code&gt; methods, &lt;code&gt;BeginX/EndX&lt;/code&gt; pattern).&lt;/p&gt;

&lt;p&gt;In conclusion, it was quite challenging to accomplish the current state of the first-class &lt;code&gt;async&lt;/code&gt; support in .NET, since it was gradually developed over the years. At the same time, it was rewarding because of the widespread acceptance of the “new/old” &lt;em&gt;async&lt;/em&gt; feature in the .NET realm. Besides, it became a &lt;em&gt;de facto&lt;/em&gt; standard when dealing with asynchronous domains like HTTP servers.&lt;/p&gt;

&lt;h2&gt;
  
  
  Command and Query — definition and model
&lt;/h2&gt;

&lt;p&gt;Unlike the complexity of &lt;em&gt;async&lt;/em&gt; domain space, CQS principle can be quite simply, yet powerfully modeled to provide a succinct, meaningful and intuitive API to work with.&lt;/p&gt;

&lt;p&gt;To begin with the &lt;a href="https://en.wikipedia.org/wiki/Command%E2%80%93query_separation"&gt;definition&lt;/a&gt;, &lt;em&gt;Command&lt;/em&gt; is a method that performs an action which &lt;strong&gt;mutates&lt;/strong&gt; the domain’s state or has any kind of side-effect. In addition to that, it doesn’t return anything. On the other hand, &lt;em&gt;Query&lt;/em&gt; is a method that performs an action which &lt;strong&gt;queries&lt;/strong&gt; the domain’s state, doesn’t produce side-effects and returns data.&lt;/p&gt;

&lt;p&gt;In both cases, there is a given set of rules (characteristics) which any method should adhere to, in order to be classified as one or the other. Moreover, there is a possibility to define the base abstract model which would guard the rules and embed characteristics into the source code, providing a necessary tool in hands to start taking the real advantage of a theoretical principle.&lt;/p&gt;

&lt;p&gt;Fair to say, it’s not mandatory to build a software library which supports the concept to start applying it daily. In many cases, even following the rules would be beneficial.&lt;/p&gt;

&lt;p&gt;But, having a reusable library built to support a certain principle gives additional room for improvements and a natural &lt;em&gt;upgrade&lt;/em&gt; of the whole concept. As described in the &lt;a href="https://dev.to/darjanbogdan/command-query-domain-introduction-5eo2"&gt;introductory&lt;/a&gt; article, &lt;em&gt;commands&lt;/em&gt;, &lt;em&gt;queries&lt;/em&gt;, and their &lt;em&gt;handlers&lt;/em&gt; could be represented using only a few generic interfaces, but they can serve as a base ground for the architecture which effortlessly supports building the software components following SOLID principles and AOP paradigm.&lt;/p&gt;

&lt;p&gt;Contrary to the mentioned abstract model which includes separate interface pairs for commands and queries, I find it more useful to unify them into a single pair. One interface to represent both (&lt;em&gt;command&lt;/em&gt; and &lt;em&gt;query&lt;/em&gt;), commonly called &lt;em&gt;request&lt;/em&gt;, and another to represent the corresponding request handler.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--mP3WfJEW--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/pl85i4fz9s9sth5tkstm.jpeg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--mP3WfJEW--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/pl85i4fz9s9sth5tkstm.jpeg" alt="Umm...I have a question?...Meme"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;I’m not the greatest fan of the term either. Firstly, it deviates from the terminology coined by CQS principle. Secondly, due to the possible association with the completely different concepts in other domains (e.g. HTTP &lt;em&gt;request&lt;/em&gt;). Nevertheless, I finally came to terms with it by simply moving the name distinction to the classes which implement before-mentioned interfaces (e.g. &lt;code&gt;CreateUserCommand : IRequest&amp;lt;TResult&amp;gt;&lt;/code&gt; and &lt;code&gt;CreateUserCommandHandler : IRequestHandler&amp;lt;CreateUserCommand, TResult&amp;gt;&lt;/code&gt;). After all, the whole abstraction is about commands, queries and their distinction — it’s worth to incorporate it somewhere.&lt;/p&gt;

&lt;p&gt;So, the main goal is to have only two base interfaces on top of which other elements will be built, something like:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight csharp"&gt;&lt;code&gt;&lt;span class="k"&gt;interface&lt;/span&gt; &lt;span class="nc"&gt;IRequest&lt;/span&gt;&lt;span class="p"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;TResult&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt; 
&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="k"&gt;interface&lt;/span&gt; &lt;span class="nc"&gt;IRequestHandler&lt;/span&gt;&lt;span class="p"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;TRequest&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;TResult&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt; 
    &lt;span class="k"&gt;where&lt;/span&gt; &lt;span class="n"&gt;TRequest&lt;/span&gt; &lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;IRequest&lt;/span&gt;&lt;span class="p"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;TResult&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt;
&lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="n"&gt;Task&lt;/span&gt;&lt;span class="p"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;TResult&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt; &lt;span class="nf"&gt;HandleAsync&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;TRequest&lt;/span&gt; &lt;span class="n"&gt;request&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;CancellationToken&lt;/span&gt; &lt;span class="n"&gt;ct&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;One could immediately say that this abstract model violates, not only the terminology but also the rules (&lt;em&gt;command&lt;/em&gt; has a return value!) defined by the abstract principle — and one would be right. However, I’m completely fine with that deviation, I’m seeing it as a reasonable theoretical model approximation caused by several (technical) limitations:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;async/await&lt;/code&gt; feature requires a method to return &lt;code&gt;Task/Task&amp;lt;T&amp;gt;&lt;/code&gt; objects to be &lt;em&gt;awaitable&lt;/em&gt; — &lt;em&gt;&lt;code&gt;async void Handle(){}&lt;/code&gt; isn’t awaitable and exceptions can’t be &lt;a href="https://jaylee.org/archive/2012/07/08/c-sharp-async-tips-and-tricks-part-2-async-void.html"&gt;handled&lt;/a&gt; in the same execution context.&lt;/em&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;void&lt;/code&gt; (&lt;a href="https://docs.microsoft.com/en-us/dotnet/api/system.void?view=netcore-2.2"&gt;&lt;code&gt;System.Void&lt;/code&gt;&lt;/a&gt;) can’t be used as a generic type parameter nor can be passed to a method — &lt;em&gt;&lt;code&gt;Task&amp;lt;void&amp;gt;&lt;/code&gt; isn’t allowed.&lt;/em&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;a href="https://docs.microsoft.com/en-us/dotnet/standard/generics/covariance-and-contravariance"&gt;Variance&lt;/a&gt; is supported by generic interface and generic delegate types only — &lt;em&gt;&lt;code&gt;class HandlerDecorator&amp;lt;in TRequest, out TResult&amp;gt;&lt;/code&gt; isn’t valid.&lt;/em&gt;&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Despite some limitations, it’s still quite important to support asynchronous programming using widely adopted &lt;a href="https://docs.microsoft.com/en-us/dotnet/standard/asynchronous-programming-patterns/task-based-asynchronous-pattern-tap"&gt;TAP&lt;/a&gt; pattern. That effectively means that interface methods must return &lt;code&gt;Task&lt;/code&gt; and/or &lt;code&gt;Task&amp;lt;T&amp;gt;&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Although, it seems that &lt;code&gt;Task HandleAsync(T command)&lt;/code&gt; method would be appropriate to use for &lt;em&gt;commands&lt;/em&gt; in asynchronous domains, it still involves violation of the principle rules. The method returns an instance of a &lt;code&gt;Task&lt;/code&gt; type, which holds the information about the method’s execution (status, exception, identifier…) and doesn’t make it truly fire-and-forget anymore. Furthermore, it would hurt reusability because it’d still be needed to have two separate interfaces for command and query handlers.&lt;/p&gt;

&lt;p&gt;To keep the possibility to represent a method which doesn’t “return” anything when having &lt;code&gt;Task&amp;lt;T&amp;gt;&lt;/code&gt; as a return type, the special &lt;code&gt;Unit&lt;/code&gt; structure must be implemented. That type indicates the absence of a specific value and often is a built-in type in functional languages, like &lt;a href="https://docs.microsoft.com/en-us/dotnet/fsharp/language-reference/unit-type"&gt;F#&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Having that in place, it’s straightforward to implement any handler which represents command or query, using the same &lt;code&gt;IRequestHandler&amp;lt;TRequest, TResult&amp;gt;&lt;/code&gt; interface:&lt;/p&gt;

&lt;p&gt;The main benefit of the singular approach lies in the possibility to reuse the same (cross-cutting) components in both cases, considering that commands and queries could share the same characteristics. Like the way of validating or authorizing them before execution, or maybe the way of preserving audit trails, or rate-limiting, and so on.&lt;/p&gt;

&lt;p&gt;Consider the following example, to implement a generic validation component for handlers, it is just necessary to build a decorator around a single &lt;code&gt;IRequestHandler&amp;lt;TRequest, TResult&amp;gt;&lt;/code&gt; interface. Otherwise, it requires practically two of them, one for &lt;code&gt;ICommandHandler&amp;lt;TCommand&amp;gt;&lt;/code&gt; and another for &lt;code&gt;IQueryHandler&amp;lt;TQuery, TResult&amp;gt;&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Similarly, any other &lt;a href="https://en.wikipedia.org/wiki/Aspect_(computer_programming)"&gt;aspect&lt;/a&gt; could be implemented (e.g. authorization, caching, …) as a single place in the code which handles the particular cross-cutting matter.&lt;/p&gt;

&lt;p&gt;It’s not only possible to chain or compose multiple decorators to technically form a &lt;em&gt;request&lt;/em&gt; pipeline, but also to conditionally apply them (generic type constraints, attributes), and automatically resolve them using &lt;em&gt;inversion of control&lt;/em&gt; techniques.&lt;/p&gt;

&lt;h2&gt;
  
  
  Result — definition and model
&lt;/h2&gt;

&lt;p&gt;The last thing which I find important to address and (optionally) incorporate into a base model is exception handling or plainly error data propagation.&lt;/p&gt;

&lt;p&gt;While it’s not mandatory to have it in place, I think it is important, especially in cases when structured error data (e.g. validation failure reasons) need to be communicated back to an API consumer.&lt;/p&gt;

&lt;p&gt;Due to the fact that it’s not possible to have more than one return type in method signatures in C#, and because there is no first-class support for &lt;a href="https://en.wikipedia.org/wiki/Tagged_union"&gt;discriminated unions&lt;/a&gt;, the easiest and the most straightforward way is to use and extend built-in exception types. So, if there is a need to return some heterogeneous data from a method, one part can be simply propagated within (custom) exception types and just thrown from a method.&lt;/p&gt;

&lt;p&gt;Still, structured error data should be treated as part of a domain, and as such should not be included inside a regular exception handling process. Besides, it’s not recommended to throw exceptions in non-exceptional scenarios (e.g. wrong input, token expiry), it makes error handling &lt;a href="https://blogs.msdn.microsoft.com/ericlippert/2008/09/10/vexing-exceptions/"&gt;vexing&lt;/a&gt; since exceptions must be handled all the time.&lt;/p&gt;

&lt;p&gt;It’s possible to avoid using custom &lt;code&gt;Exception&lt;/code&gt; as a carrier of the domain-related data, by “borrowing” and implementing generic &lt;a href="https://docs.microsoft.com/en-us/dotnet/fsharp/language-reference/results"&gt;Result&lt;/a&gt; structure, usually found in functional-first languages.&lt;/p&gt;

&lt;p&gt;There are many different ways to implement structure alike in C#, as it is usually based on &lt;a href="https://blog.ploeh.dk/2018/06/11/church-encoded-either/"&gt;Church-encoded&lt;/a&gt; &lt;em&gt;Either&lt;/em&gt; abstraction, which is represented with a single interface method:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight csharp"&gt;&lt;code&gt;&lt;span class="k"&gt;interface&lt;/span&gt; &lt;span class="nc"&gt;IEither&lt;/span&gt;&lt;span class="p"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;TLeft&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;TRight&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt;
&lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="n"&gt;T&lt;/span&gt; &lt;span class="n"&gt;Match&lt;/span&gt;&lt;span class="p"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;T&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;(&lt;/span&gt;&lt;span class="n"&gt;Func&lt;/span&gt;&lt;span class="p"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;TLeft&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;T&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;left&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;Func&lt;/span&gt;&lt;span class="p"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;TRight&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;T&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;right&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;For the sake of clarity and intuitiveness, instead of using highly abstract &lt;em&gt;Either&lt;/em&gt; term, &lt;em&gt;Result&lt;/em&gt; will be used. The name more closely describes the intent and is more fitting in every-day conversation.&lt;/p&gt;

&lt;p&gt;If incorporated as-is into the request handler interface, three generic type parameters must be exposed (i.e. &lt;code&gt;IRequestHandler&amp;lt;TRequest, TResponse, TError&amp;gt;&lt;/code&gt;) which adds additional complexity to the model. Also, the whole interface looks quite tedious to work with.&lt;/p&gt;

&lt;p&gt;Most of the times, such a degree of model extensibility isn’t required at all and unification of all &lt;em&gt;errors&lt;/em&gt; under common type is recommended — there is rarely a need to work with different &lt;em&gt;error&lt;/em&gt; types. In that case &lt;code&gt;TError&lt;/code&gt; generic type parameter can be omitted and suitable non-generic &lt;code&gt;Error&lt;/code&gt; type used instead — making the generic &lt;code&gt;Result&lt;/code&gt; class simpler and final version of handler interface cleaner:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight csharp"&gt;&lt;code&gt;&lt;span class="k"&gt;interface&lt;/span&gt; &lt;span class="nc"&gt;IRequestHandler&lt;/span&gt;&lt;span class="p"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;TRequest&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;TResponse&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt; 
    &lt;span class="k"&gt;where&lt;/span&gt; &lt;span class="n"&gt;TRequest&lt;/span&gt; &lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;IRequest&lt;/span&gt;&lt;span class="p"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;TResponse&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&lt;/span&gt;
&lt;span class="p"&gt;{&lt;/span&gt;    
    &lt;span class="n"&gt;Task&lt;/span&gt;&lt;span class="p"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;Result&lt;/span&gt;&lt;span class="p"&gt;&amp;lt;&lt;/span&gt;&lt;span class="n"&gt;TResponse&lt;/span&gt;&lt;span class="p"&gt;&amp;gt;&amp;gt;&lt;/span&gt; &lt;span class="nf"&gt;HandleAsync&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
        &lt;span class="n"&gt;TRequest&lt;/span&gt; &lt;span class="n"&gt;request&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; 
        &lt;span class="n"&gt;CancellationToken&lt;/span&gt; &lt;span class="n"&gt;cancellationToken&lt;/span&gt;
    &lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;There are many &lt;em&gt;quality-of-life&lt;/em&gt; details which could be added to the abstract model to furtherly enhance every-day usage, such as implicit conversion into &lt;code&gt;Result&amp;lt;T&amp;gt;&lt;/code&gt;, set of various helper methods, more derived interfaces, etc.&lt;/p&gt;

&lt;p&gt;All these details can be seen in the more comprehensive and complete model shown in &lt;em&gt;Pype&lt;/em&gt; &lt;a href="https://github.com/darjanbogdan/pype/tree/master/src/Pype"&gt;repository&lt;/a&gt;. The repository will be gradually expanded with the components which will be covered throughout the article series.&lt;/p&gt;

&lt;p&gt;Besides that, it’s worth mentioning &lt;a href="https://github.com/jbogard/MediatR"&gt;MediatR&lt;/a&gt; and &lt;a href="https://github.com/daniellittledev/Enexure.MicroBus"&gt;Microbus&lt;/a&gt; libraries which are modeling the same principle, both providing similar generic interfaces, but each has some specifics and additional features.&lt;/p&gt;

&lt;p&gt;In the &lt;a href="https://dev.to/darjanbogdan/command-query-domain-mediator-kn7"&gt;next&lt;/a&gt; chapter, request handler mediator and request pipeline composition will be covered!&lt;/p&gt;




&lt;p&gt;&lt;em&gt;All the gists, examples or solutions will be done in C# using the latest .Net Core/Standard versions and hosted on &lt;a href="https://github.com/darjanbogdan?utf8=%E2%9C%93&amp;amp;tab=repositories&amp;amp;q=pype&amp;amp;type=public&amp;amp;language=c%23"&gt;Github&lt;/a&gt;.&lt;/em&gt;&lt;/p&gt;

</description>
      <category>csharp</category>
      <category>dotnet</category>
      <category>oop</category>
      <category>cqs</category>
    </item>
    <item>
      <title>Command &amp; Query: Domain  - Introduction</title>
      <dc:creator>Darjan Bogdan</dc:creator>
      <pubDate>Tue, 18 Aug 2020 06:13:48 +0000</pubDate>
      <link>https://dev.to/darjanbogdan/command-query-domain-introduction-5eo2</link>
      <guid>https://dev.to/darjanbogdan/command-query-domain-introduction-5eo2</guid>
      <description>&lt;p&gt;&lt;em&gt;The story is a part of the series about software architecture powered by command-query separation principle and aspect-oriented programming.&lt;/em&gt;&lt;/p&gt;




&lt;h2&gt;
  
  
  Introduction and motivation
&lt;/h2&gt;

&lt;p&gt;Reading through discussion threads about &lt;a href="https://martinfowler.com/bliki/CQRS.html" rel="noopener noreferrer"&gt;CQRS&lt;/a&gt; pattern, I often get the feeling that the general impression about the topic could be summarized into the following:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;em&gt;The whole concept seems pretty reasonable, and the idea behind it solid, but it looks like overkill for non-enterprise projects, I’d rather stick to…&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Although I do understand such reasoning, I still think that initial skepticism is rooted in the fact that there is no clear way of taking advantage of a higher abstraction which sits behind the pattern. It simply feels that the implementation effort is too great and doesn’t pay off in “smaller” code bases. However, I strongly disagree with that.&lt;/p&gt;

&lt;p&gt;Particularly, I think the size of a project shouldn’t be a determining factor to choose a certain approach, but rather its domain flexibility and compatibility. While it’s pretty much clear that there is no single architectural pattern (principle, abstraction) which would perfectly fit any domain, in a plethora of cases, &lt;a href="https://en.wikipedia.org/wiki/Command%E2%80%93query_separation" rel="noopener noreferrer"&gt;CQS&lt;/a&gt; principle could be adapted and fairly successfully applied.&lt;/p&gt;

&lt;p&gt;At first, I was suspicious to use the pattern in a production world, especially since the &lt;a href="https://en.wikipedia.org/wiki/Domain_model" rel="noopener noreferrer"&gt;Domain model&lt;/a&gt; or classical &lt;a href="https://en.wikipedia.org/wiki/Multitier_architecture" rel="noopener noreferrer"&gt;N-layered&lt;/a&gt; approaches felt much closer and overall friendlier.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fqr4oyz5t0ob9dqe4qnu6.jpeg" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fqr4oyz5t0ob9dqe4qnu6.jpeg" alt="One does not simply... Meme"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;At that time, I simply didn’t know that &lt;em&gt;Command and Query Separation&lt;/em&gt; principle, as an abstraction, could be modeled quite powerfully. The whole concept could be represented using a few interfaces in C#, for example :&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;Examining such model, thoroughly described in the &lt;em&gt;Meanwhile… on the &lt;a href="https://blogs.cuttingedge.it/steven/posts/2011/meanwhile-on-the-command-side-of-my-architecture/" rel="noopener noreferrer"&gt;command&lt;/a&gt;/&lt;a href="https://blogs.cuttingedge.it/steven/posts/2011/meanwhile-on-the-query-side-of-my-architecture/" rel="noopener noreferrer"&gt;query&lt;/a&gt; side of my architecture&lt;/em&gt; posts, &lt;a href="https://livebook.manning.com/#!/book/dependency-injection-principles-practices-patterns/chapter-10/" rel="noopener noreferrer"&gt;Chapter 10&lt;/a&gt; of the &lt;em&gt;Dependency Injection Principles, Practices, and Patterns&lt;/em&gt; book and others, it quickly becomes apparent how adaptable and flexible it is. In addition, carefully designed interfaces restrict the developer from abusing such a general principle and give core building blocks to accomplish greater and more complex architectures.&lt;/p&gt;

&lt;p&gt;Developers have all the freedom to tailor a software solution to its domain’s needs. Practically, no other factors dictate that it must be a fully-fledged CQRS solution with distributed persistence stores and messaging bus in between. Therefore, there is no single reason not to (try) to apply a CQS principle in a project which is not of “enterprise” size, once the concept becomes clear enough.&lt;/p&gt;

&lt;p&gt;It’s obvious that the implementation complexity of a certain theoretical pattern is influenced by the developer. When needed it’s acceptable to do a trade-off between the purity of theoretical concept and practical implementation. Especially, if it would enhance maintainability and reduce the overall complexity of the code base.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fq6swfg8n17dwvbu7blef.jpeg" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fq6swfg8n17dwvbu7blef.jpeg" alt="Science vs Engineering... Meme"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The whole series will be focused on showing and exploring practical implementation of CQS principle, built around a generic model which doesn’t fully follow the theoretical concept. The most surprising thing is that you could be perfectly fine if the &lt;em&gt;Command&lt;/em&gt; returns a result, however under certain rules and discipline.&lt;/p&gt;

&lt;p&gt;Many topics will be addressed along the way. Essential parts first — to get a general understanding of the approach, and then, gradually, other building blocks will be incorporated into the whole picture.&lt;/p&gt;

&lt;p&gt;Series should act as a hands-on guide to the world of commands and queries. Starting from the base model introduction and later extending it with many cross-cutting aspects, molding it into a data processing pipeline.&lt;/p&gt;

&lt;p&gt;The goal is to understand how to assemble a typical API server using the following building blocks:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Command and Query&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Cross-cutting Aspects&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Pipeline and Context&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Messaging and Eventing&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;For each concept, feasible models will be presented and described, including their pros and cons. Even though the implementation is usually opinionated, I’ll try to keep the spotlight on the parts which are more or less universal and only explain important details of the underlying technologies and/or libraries.&lt;/p&gt;

&lt;p&gt;Ultimately, the whole code base should adhere to &lt;a href="https://en.wikipedia.org/wiki/SOLID" rel="noopener noreferrer"&gt;SOLID&lt;/a&gt; principles practically out of the box which again leads to many great things like modularity, maintainability, reusability and many more.&lt;/p&gt;

&lt;p&gt;In the &lt;a href="https://dev.to/darjanbogdan/command-query-domain-abstract-model-662"&gt;next&lt;/a&gt; chapter &lt;em&gt;Command&lt;/em&gt; and &lt;em&gt;Query’s&lt;/em&gt; abstraction will be examined and the base model described, on top of which other parts will be built.&lt;/p&gt;




&lt;p&gt;&lt;em&gt;All the gists, examples, or solutions will be done in C# using the latest .Net Core/Standard versions and hosted on &lt;a href="https://github.com/darjanbogdan?tab=repositories" rel="noopener noreferrer"&gt;Github&lt;/a&gt;.&lt;/em&gt;&lt;/p&gt;

</description>
      <category>csharp</category>
      <category>dotnet</category>
      <category>oop</category>
      <category>cqs</category>
    </item>
  </channel>
</rss>
