Tester/Doer pattern: Assume the caller conforms to the pattern or be defensive and repeat the check?

Posted by Daniel Hilgarth on Programmers See other posts from Programmers or by Daniel Hilgarth
Published on 2013-06-26T16:10:44Z Indexed on 2013/06/26 16:28 UTC
Read the original article Hit count: 206

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?

© Programmers or respective owner

Related posts about design-patterns

Related posts about architecture