Thursday, November 13, 2008

Refactoring: Replace Conditional Dispatcher with Command

Quote from the book Refactoring to Patterns:

Conditional logic is used to dispatch requests and execute actions.

Create a Command for each action. Store the Commands in a collection and replace the conditional logic with code to fetch and execute Commands.

The main idea is to create a command for each action, and then create a sort of command lookup class to lookup the request and delegate to the command.

This can work very well if you can easily decide what command should be taken from the request. Actually, in PHP web development, command pattern might be the most common pattern.

However, things become a little hard if you cannot easily find out the corresponding command to the request. In this situation, I would think of chain of command. Let each command decide if it should process the request by itself. If it should, it will process it and stop, otherwise, the request will be passed to the next command and so on.

No comments: