CQRS - Command/Query single parameter - cqrs

All the examples showcasing the CQRS pattern always have 0 or 1 parameter.
For example:
public class MyCommand
{
public int Value { get; set; }
}
public class MyCommandHandler
{
public void Handle(MyCommand myCommand)
{ ... }
}
Assuming we are calling the handle directly is there is any reason besides the implementation details?
I'm aware of the advantages of having a single parameter, like encapsulating all the required data to perform the action and also making it easier to serialize if we have to work with Queues of Q/C, validation, etc..
But is it "wrong" to have multiple parameters in the handler?

But is it "wrong" to have multiple parameters in the handler?
No; it's tradeoffs.
When we have handlers with incompatible signatures, then composing handlers -- for instance, creating a handler with some cross cutting concerns -- takes more work because of the number of variations required.

No, it is not, I would say that it is sometimes advisable to use multiple parameters to separate concerns. Because you might have traceID, correlationID, or other types of technical data that you don't want to combine with business data. When you send a request, you are using headers, so when sending a message for handling, headers can be used as well
public class MyCommandHandler
{
public void Handle(MyCommand myCommand, MyHeader $header, MySecondHeader $secondHeader)
}
Also, if you don't want to inject dependencies in constructor for whatever reason, it is ok to inject them as parameters.

Related

CQRS Commands and Events as generic classes?

In most examples I saw, commands and events are represented as classes. That means you have to write a CorrectNameCommand class with name property and a NameCorrectedEvent class with name property. Given that both commands and events are serialized and deserialized in most cases and send to other parties (there goes the compile time type safety), what is the advantage of this explicit classes over a more generic class?
Example:
A Command class with a Name (that represents the type of the command), the key of the ag that should handle the command and an array of objects or name/value pairs for any other parameters.
An Event class essentially the same (perhaps we can put the shared parts in an CommandEventBase class).
The command (and event) handlers have now to check the name of the command (event) instead of its class type and have to rely on the correctness of the parameters in the list (like the deserializer has to rely that the serialized format is correct).
Is that a good approach? If yes, why is it not used in the samples and tutorials? If not, what are the problems?
Duplication
It's a fair point that when Commands and Events are serialized, compile-time safety is lost, but in a statically typed language, I'd still prefer strongly typed Command and Event types.
The reason for this is that it gives you a single piece of the code base responsible for interpreting message elements. Serialization tends to be quite (type-)safe; deserialization is where you may encounter problems.
Still, I'd prefer to deal with any such problems in a single place, instead of spread out over the entire code base.
This is particularly relevant for Events, since you may have multiple Event Handlers handling the same type of Event. If you treat events as weakly typed dictionaries, you'll need to duplicate the implementation of a Tolerant Reader in each and every Event Handler.
On the other hand, if you treat Events and Commands as strong types, your deserializer can be the single Tolerant Reader you'd have to maintain.
Types
All this said, I can understand why you, in languages like C# or Java, find that defining immutable DTOs for each and every message seems like a lot of overhead:
public sealed class CorrectNameCommand
{
private readonly string userId;
private readonly string newName;
public CorrectNameCommand(string userId, string newName)
{
this.userId = userId;
this.newName = newName;
}
public string UserId
{
get { return this.userId; }
}
public string NewName
{
get { return this.newName; }
}
public override bool Equals(object obj)
{
var other = obj as UserName;
if (other == null)
return base.Equals(obj);
return object.Equals(this.userId, other.userId)
&& object.Equals(this.newName, other.newName);
}
public override int GetHashCode()
{
return this.userId.GetHashCode() ^ this.newName.GetHashCode();
}
}
That, indeed, seems like a lot of work.
This is the reason that I these days prefer other languages for implementing CQRS. On .NET, F# is a perfect fit, because all of the above code boils down to this one-liner:
type CorrectNameCommand = { UserId : string; NewName : string }
That's what I'd do, instead of passing weakly typed dictionaries around. Last time I heard Greg Young talk about CQRS (NDC Oslo 2015), he seemed to have 'converted' to F# as well.

Maximum number of related records

Is there a way to specify the maximum number of related records allowed for an entity? For example, for each Order entity I want to specify a constraint that it has a maximum of five orderItems.
Would I have to use sql or is there something in the fluent api or ef attributes that can help?
I think that "a maximum of five orderItems per order" is a business requirement. Such requirements should not be implemented by infrastructure (mapping) or sql (although I'm not sure what you mean by that, I read it as database logic). An attribute that causes validation might be OK, but I don't think there is any attribute for it.
You should implement it in a way that validation and feedback occur similar to all other business rules. Rules implemented in mapping (if it were possible) or database constraints would require a second validation mechanism, probably catching exceptions, which is ugly.
Besides that, it is a rule that could change one day, maybe even temporarily (Christmas?). Then you don't want the implementation of this rule to be scattered over various application layers.
I would implement the rule in some AddItem method in a service class or repository or in the Order class itself and make the maximum configurable.
I would approach this something like what was done here:
Limit size of Queue<T> in .NET?
Also: How do I override List<T>'s Add method in C#?
Handle this by overriding whatever is handling you list of returned entities with an extended type which implements your business logic requirements. This will also make it easy to control the property from a settings file if you want to change it in the future.
I know of no way to do this in either EF / Fluent or SQL and it seems counter intuitive as this is relevant business logic and not relevant to how you persist the data. (*Not to say there isn't a way I don't know of)
Something like this should work:
public class LimitedList<T> : List<T> {
private int limit = -1;
public int Limit {
get { return limit; }
set { limit = value; }
}
private List<T> list= new List<T>();
public LimitedList(int Limit) {
this.Limit=Limit;
}
public void Add(T entry) {
if (this.Limit != list.Count) {
list.Add(entry);
} else {
//error
}
}
}

GWT RequestFactory and multiple types

My GWT app has ten different kinds of entities. Right now I use plain old DTOs and transport them over GWT-RPC. This works well for cases like startup - I can pack them all into a single request.
I'm looking at switching to RequestFactory because there are many times throughout the lifetime of the app (30 minutes, on average) when I just have to update one type of entity, and the unifying/bandwidth-saving features of RequestFactory are appealing. BUT: I don't see a way to download all of my initialization data in a single request when the app loads. I don't want to have to make ten requests to fetch all of the init data for my ten entity types.
Is there a way to make a GeneralRequestContext, or something? I'd even be happy with a solution like:
public interface InitDataProxy extends EntityProxy
{
public UserProxy getInitUsers();
public OrganizationProxy getInitOrganizations();
...
}
public interface GeneralRequestContext extends RequestContext
{
Request<InitDataProxy> getInitData();
}
But this won't work because I don't want to have to actually back InitDataProxy with anything, I just want to use it to combine a bunch of different types of Proxies in a single request.
So: Is there a way to receive multiple, unrelated types of EntityProxy in a single request?
I would also be happy enough making a normal gwt-rpc request to go outside of RequestFactory for this data, but I don't want to have to implement duplicate DTOs to run next to RequestFactory's proxies, and write custom code to copy the DTOs into them!
The InitDataProxy could extend ValueProxy instead, which doesn't require that the object on the server have any kind of id or version semantics. The domain-side InitData type could be an interface, possibly implemented with an anonymous type.
interface InitData {
User getUser();
Organization getOrgatization();
}
class InitService {
static InitData makeInitData() {
return new InitData() { ..... };
}
}
#ProxyFor(InitData.class)
interface InitDataProxy extends ValueProxy {
UserProxy getUser();
OrganizationProxy getOrganization();
}
#Service(InitService.class)
interface Init extends RequestContext {
Request<InitDataProxy> makeInitData();
}

Class design: file conversion logic and class design

This is pretty basic, but sort of a generic issue so I want to hear what people's thoughts are. I have a situation where I need to take an existing MSI file and update it with a few standard modifications and spit out a new MSI file (duplication of old file with changes).
I started writing this with a few public methods and a basic input path for the original MSI. The thing is, for this to work properly, a strict path of calls has to be followed from the caller:
var custom = CustomPackage(sourcemsipath);
custom.Duplicate(targetmsipath);
custom.Upgrade();
custom.Save();
custom.WriteSmsXmlFile(targetxmlpath);
Would it be better to put all the conversion logic as part of the constructor instead of making them available as public methods? (in order to avoid having the caller have to know what the "proper order" is):
var custom = CustomPackage(sourcemsipath, targetmsipath); // saves converted msi
custom.WriteSmsXmlFile(targetxmlpath); // saves optional xml for sms
The constructor would then directly duplicate the MSI file, upgrade it and save it to the target location. The "WriteSmsXmlFile is still a public method since it is not always required.
Personally I don't like to have the constructor actually "do stuff" - I prefer to be able to call public methods, but it seems wrong to assume that the caller should know the proper order of calls?
An alternative would be to duplicate the file first, and then pass the duplicated file to the constructor - but it seems better to have the class do this on its own.
Maybe I got it all backwards and need two classes instead: SourcePackage, TargetPackage and pass the SourcePackage into the constructor of the TargetPackage?
I'd go with your first thought: put all of the conversion logic into one place. No reason to expose that sequence to users.
Incidentally, I agree with you about not putting actions into a constructor. I'd probably not do this in the constructor, and instead do it in a separate converter method, but that's personal taste.
It may be just me, but the thought of a constructor doing all these things makes me shiver. But why not provide a static method, which does all this:
public class CustomPackage
{
private CustomPackage(String sourcePath)
{
...
}
public static CustomPackage Create(String sourcePath, String targetPath)
{
var custom = CustomPackage(sourcePath);
custom.Duplicate(targetPath);
custom.Upgrade();
custom.Save();
return custom;
}
}
The actual advantage of this method is, that you won't have to give out an instance of CustomPackage unless the conversion process actually succeeded (safe of the optional parts).
Edit In C#, this factory method can even be used (by using delegates) as a "true" factory according to the Factory Pattern:
public interface ICustomizedPackage
{
...
}
public class CustomPackage: ICustomizedPackage
{
...
}
public class Consumer
{
public delegate ICustomizedPackage Factory(String,String);
private Factory factory;
public Consumer(Factory factory)
{
this.factory = factory;
}
private ICustomizedPackage CreatePackage()
{
return factory.Invoke(..., ...);
}
...
}
and later:
new Consumer(CustomPackage.Create);
You're right to think that the constructor shouldn't do any more work than to simply initialize the object.
Sounds to me like what you need is a Convert(targetmsipath) function that wraps the calls to Duplicate, Upgrade and Save, thereby removing the need for the caller to know the correct order of operations, while at the same time keeping the logic out of the constructor.
You can also overload it to include a targetxmlpath parameter that, when supplied, also calls the WriteSmsXmlFile function. That way all the related operations are called from the same function on the caller's side and the order of operations is always correct.
In such situations I typicaly use the following design:
var task = new Task(src, dst); // required params goes to constructor
task.Progress = ProgressHandler; // optional params setup
task.Run();
I think there are service-oriented ways and object-oritented ways.
The service-oriented way would be to create series of filters that passes along an immutable data transfer object (entity).
var service1 = new Msi1Service();
var msi1 = service1.ReadFromFile(sourceMsiPath);
var service2 = new MsiCustomService();
var msi2 = service2.Convert(msi1);
service2.WriteToFile(msi2, targetMsiPath);
service2.WriteSmsXmlFile(msi2, targetXmlPath);
The object-oriented ways can use decorator pattern.
var decoratedMsi = new CustomMsiDecorator(new MsiFile(sourceMsiPath));
decoratedMsi.WriteToFile(targetMsiPath);
decoratedMsi.WriteSmsXmlFile(targetXmlPath);

IoC, Mixing injections with parameters in the constructor?

I am new to Inversion of Control (IoC), so I wanted to know the best strategy to handle
the case where I want to pass data structures/parameters as well as injected
objects into a class.
A simple example:
public class EmailSender
{
public EmailSender(string toEmail, string Subject, String body,
ILogger emailLogger)
{.....}
}
What is the best strategy here? I guess it's not possible to inject directly?
I guess I need to put all the string parameters as setters instead and
just have the Ilogger in the constructor, or the other way around?
Or am I wrong?
P.s. I know the example above sucks and toEmail and body should be passed in a separate method call, but it was just to make an example.
No, you should be able to specify the strings in the constructor call. Admittedly I'd usually expect those to be more "transient" values passed in as method arguments:
public class EmailSender
{
private readonly ILogger emailLogger;
public EmailSender(ILogger emailLogger)
{
this.emailLogger = emailLogger;
}
public void SendEmail(string toEmail, string subject, string body)
{
// ...
}
}
That way the same EmailSender can be used to send many emails - the details of the email itself "flow through" the sender rather than being part of it.
EDIT: Given the edit to the question, it's not entirely clear what remains. If you're really asking how to specify strings as constructor arguments, that will depend on the IoC framework you're using. If you could specify the framework, we could probably give you the appropriate syntax.