Is it OK to have more than one handler for a command in CQRS? - cqrs

As title says, is it OK to have more than one handler for a command in CQRS? Looking at the simple CQRS example here and this line made me confused.
Here is the code:
public void Send<T>(T command) where T : Command
{
List<Action<Message>> handlers;
if (_routes.TryGetValue(typeof(T), out handlers))
{
if (handlers.Count != 1) throw new InvalidOperationException("cannot send to more than one handler");
handlers[0](command);
}
else
{
throw new InvalidOperationException("no handler registered");
}
}
However, we have list of handlers per command type there which makes me more confused :) I am guessing that it's just an implementation detail and in ideal world, it should be OK but I wanted to be sure.

You should have just one command handler for a command. Commands are sent to request a change in the domain. Their implementation can be similar to DTOs, but they are not only transfer data. They provide communication in the abstract. So if there is one Command which has a general purpose and handled by lots of command handlers, this means that there is a separate logic on that command. And this can create inconsistency in domain. It will be difficult to find which handler is used for a specific command request.
And also when you change(add a property) the command for one specific command handler, that change is meaningless for other command handlers. And that is not desired.
If you need a concept like handling one command with more than one handlers, consider event sourcing which is also mentioned in CQRS.

Related

jBPM signal event does always complete work item

I've implemented a custom workitemhandler which I want to complete only by an external REST call. Therefore the items executeWorkItem() method does NOT call manager.completeWorkItem(workItem.getId(), results); at the end, which is perfectly ok. I've also assigned a signal event to this workitem in my process, which is also called by an external REST call. Both things work as expected, but what I do not understand is that every time I signal the work item, it also automatically completes the work item, which leads to the problem that the process continuous with its regular path AND the signaled one. But the reason for the signal is to interrupt the process to follow ONLY the signaled path path.
The process image to this can be found here http://cl.ly/image/0F3L3E2w2l0j. In this example I signaled the "Fail Transfer" but the rest gets also executed even nothing completed the workitem.
I'm using jBPM 6.1 Final.
Thanks in advance for any help.
Nevermind, I found the reason for this behavior. The custom work item handler implemented
public void abortWorkItem(WorkItem workItem, WorkItemManager manager) {
manager.abortWorkItem(workItem.getId());
}
After removing manager.abortWorkItem(workItem.getId());, the process behaves as expected.

Accumulated methods invocation order in RequestContext#fire()?

Javadoc for RequestContext#fire() says only:
Send the accumulated changes and method invocations associated with the RequestContext.
GWT Moving Parts wiki entry under Flow section says only:
All accumulated operations will be applied to the domain objects by traversing properties of the proxies.
All method invocations in the payload are executed.
But will these methods be executed on the server side in the same order they were "executed" (accumulated) on ReqestContext instance on client side?
For my situation, if I execute on client side:
context.persist().using(proxy)
context.find(proxy.stableId().to(updatingReceiver))
context.fire()
Then may I be sure that on server side find() will be invoked after persist() so my updatingReceiver will get proxy of updated (persist()'ed) entity as an argument?
EDIT:
Going further, may I be sure that back on client after response Recievers will be invoked in exactly the same order in which their corresponding methods were accumulated?
Finally, is there a way to add some action that will be invoked at the end of response handling, after all Receivers' actions?
I thought something like this may work:
requestContext.fire(new Receiver<Void>() {
#Override
public void onSuccess(Void response) {
//Things to do after all receivers
});
And it really seems to work as I expected but because all that Javadoc is telling me about RequestContext.fire(Receiver) method is:
For receiving errors or validation failures only.
I'm not 100% sure whether my assumption is correct.
Yes, order of method invocations is preserved, both on the server-side and then back on the client side when calling Recievers.
The queue is a simple ArrayList in which invocation objects are appended. On the server-side, they're processed in the order they're received.
The Request-Context-level Receiver is always called after the ones for invocations. Its onSuccess is always called, whatever the result of the invocations (even if they all fail), to signal that the batch of invocations was processed successfully. Its onFailure is only called in case of a general failure, i.e. a network error, or an error when (de)serializing requests/responses on the server-side.
See http://code.google.com/p/google-web-toolkit/source/browse/trunk/user/src/com/google/web/bindery/requestfactory/shared/impl/AbstractRequestContext.java?r=10835#345

How is Callback handling implemented?

In the past, I have used libraries that would allow me to register a callback so that the library can call my method when some event happens (e.g. it is common to see in code that use GUI libraries to look like button.onClick(clickHandler)).
Naively, I suppose the library's handling mechanism could be implemented like:
while(1){
if (event1) { event1Handler(); }
if (event2) { event2Handler(); }
...
}
but that would be really wasteful right? Or is that really how it is done (for instance do well known GUI libraries like java swing, or GTK+ do it this way)?
background:
This question hadn't really occured to me until I encountered curses. I thought about implementing my own callback system, until I realized I didn't know how.
The while loop will typically wait for an interrupt from the user (GetMessage in Windows). When an interrupt arrives GetMessage returns and then it ends up in the callback function. The if statements are typically implemented as a switch-case. See Windows Message Loop on Wikipedia.
In more detail, what happens is the following:
The user application calls GetMessage, which forces the process to sleep until an input message for that application arrives from the systems queue. When a message arrives, the user app calls DispatchMessage, which calls the callback function associated with the window that the message was aimed at.
Windows API uses one callback which handles all events in a switch case. Other libraries use one callback per event class instead.
The function pointers themselves are stored together with other window data in a struct.
Callback system implementation probably has different implementation in different technologies, however, I suppose they should be working this way:
A data structure stores the callback IDs and pointers to the handlers.
A callback handler has a validator
Event handlers have callback callers, which know what are the possible callbacks and check their validity this way:
for each callback in event.callbacks
if (callback.isValid())
call callback()
end if
end for
When you add a handler to a function the system will automatically know where the callback is valid and will add the callback to the datastructure described in 1.
Correct me if I'm wrong, this description is just a guess.

What Event Handler to Subscribe and Assert.AreEqual Fails

I want to invoke a method when my integration test fails (i.e., Assert.AreEqual fails), is there any event delegate that I can subscribe to in NUnit framework? Of course the event delegate must be fired when the tests fail.
This is because in my tests there are a lot of Assert statement, and I can't tell need to log the Assert, along with the assertion information that cause a problem in my bug tracker. The best way to do this is to when the test fails, a delegate method is invoke.
I'm curious, what problem are you trying to solve by doing this? I don't know of a way to do this with NUnit, but there is a messy way to do it. You can supply a Func and invoke it as the fail message. The body of the Func can provide you delegation you're looking for.
var callback = new Func<string>(() => {
// do something
return "Reason this test failed";
});
Assert.AreEqual("", " ", callback.Invoke());
It seems that there is no event I can subscribe to in case of assert fail
This sounds like you are wanting to create your own test-runner.
There is a distinction between tests (a defines the actions) and the running of the tests (actually running the tests). In this case, if you want to detect that a test failed, you would have to do this when the test is run.
If all you are looking to do is send an email on fail, it may be easiest to create a script (powershell/batch) that runs the command line runner, and sends an email on fail (to your bug tracking system?)
If you want more complex interactivity, you may need to consider creating a custom runner. The runner can run the test and then take action based on results. In this case you should look in the Nunit.Core namespace for the test runner interface.
For example (untested):
TestPackage package = new TestPackage();
package.add("c:\some\path\to.dll");
SimpleTestRunner runner = new SimpleTestRunner();
if (runner.Load(Package)){
var results = runner.Run(new NullListener(), TestFilter.Empty, false, LoggingThreshold.Off);
if(results.ResultState != ResultState.Success){
... do something interesting ...
}
}
EDIT: better snippet of code https://stackoverflow.com/a/5241900/1961413

Rhino Mocks Calling instead of Recording in NUnit

I am trying to write unit tests for a bit of code involving Events. Since I need to raise an event at will, I've decided to rely upon RhinoMocks to do so for me, and then make sure that the results of the events being raised are as expected (when they click a button, values should change in a predictable manner, in this example, the height of the object should decrease)
So, I do a bit of research and realize I need an Event Raiser for the event in question. Then it's as simple as calling eventraiser.Raise(); and we're good.
The code for obtaining an event raiser I've written as is follows (written in C#) (more or less copied straight off the net)
using (mocks.Record())
{
MyControl testing = mocks.DynamicMock<MyControl>();
testing.Controls.Find("MainLabel",false)[0].Click += null;
LastCall.IgnoreArguments();
LastCall.Constraints(Rhino.Mocks.Constraints.Is.NotNull());
Raiser1 = LastCall.GetEventRaiser();
}
I then test it as In playback mode.
using (mocks.Playback())
{
MyControl thingy = new MyControl();
int temp=thingy.Size.Height;
Raiser1.Raise();
Assert.Greater(temp, thingy.Size.Height);
}
The problem is, when I run these tests through NUnit, it fails. It throws an exception at the line testing.Controls.Find("MainLabel",false)[0].Click += null; which complains about trying to add null to the event listener. Specifically, "System.NullReferenceException: Object Reference not set to an instance of the Object"
Now, I was under the understanding that any code under the Mocks.Record heading wouldn't actually be called, it would instead create expectations for code calls in the playback. However, this is the second instance where I've had a problem like this (the first problem involved classes/cases that where a lot more complicated) Where it appears in NUnit that the code is actually being called normally instead of creating expectations. I am curious if anyone can point out what I am doing wrong. Or an alternative way to solve the core issue.
I'm not sure, but you might get that behaviour if you haven't made the event virtual in MyControl. If methods, events, or properties aren't virtual, then I don't think DynamicMock can replace their behaviour with recording and playback versions.
Personally, I like to define interfaces for the classes I'm going to mock out and then mock the interface. That way, I'm sure to avoid this kind of problem.