Assume a simple class that implements the Tester/Doer pattern:
public class FooCommandHandler : ICommandHandler
{
public bool CanHandle(object command)
{
return command is FooCommand;
}
public void Handle(object command)
{
var fooCommand = (FooCommand)command;
// Do something with fooCommand
}
}
Now, if someone doesn't conform to the pattern and calls Handle
without verifying the command via CanHandle
, the code in Handle
throws an exception.
However, depending on the actual implementation of Handle
this can be a whole range of different exceptions.
The following implementation would check CanHandle
again in Handle
and throw a descriptive exception:
public void Handle(object command)
{
if(!CanHandle(command))
throw new TesterDoerPatternUsageViolationException("Please call CanHandle first");
// actual implementation of handling the command.
}
This has the advantage that the exception is very descriptive.
It has the disadvantage that CanHandle
is called twice for "good" clients.
Is there a consensus on which variation should be used?
Handle()
so that it only takes aFooCommand
?ICommandHandler
for different commands. All those handlers are registered at a central location (the command dispatcher). It iterates over all registered commands and callsHandle
only on those thatCanHandle
the current command. You can't implement something like this with generics, because you wouldn't be able to put them in a list.ICommandHandler<T> : ICommandHandler
, storing asList<ICommandHandler> commands
, and retrieving withcommands.Where(x => x is ICommandHandler<FooCommand>)
?