Tester/Doer pattern: Assume the caller conforms to the pattern or be defensive and repeat the check?
- by Daniel Hilgarth
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?