command pattern returning status

Stefano Borini picture Stefano Borini · Jul 20, 2009 · Viewed 10.7k times · Source

Once I had a discussion about design, relative to the command pattern. My peer stated that a command object should not return the status (successful, unsuccessful, and why) after the .execute() method is called. The reason is that you should not be concerned if the command gets executed or not, because the command must contain no state. You must however check after the invocation if the command had the expected effect. Another point he argued was that on the Gang of Four, the command pattern does not present this case (of returning status).

I claimed the opposite point. The GoF does not present this case, but a pattern can be modeled to your needs. If a command is unsuccessful, the invoking client must receive a proof of the status, and eventually deploy an appropriate reaction. By forcing the client to check if the action achieved success was error prone and produced duplicated code. Moreover, there are cases where the command produces a result (eg. a command that adds a line to a plot, will somehow have the line id to return to the client), and pretending to have commands with no state meant that you had to "fish out" the new object identifier from the data model.

In the end, we reached a compromise by not returning status but keeping the id's of newly created objects in the command object, and the application worked pretty well anyway, but I am now curious to know your opinion as well.

Answer

Thomas Owens picture Thomas Owens · Jul 20, 2009

I don't have Design Patterns: Elements of Reusable Object-Oriented Software in front of me at the moment, but I'm pretty sure the authors even say that the design patterns they present are a model that can be modified to fit a specific situation.

This question cuts to the core of what a design pattern is - a template. It's not something that must be implemented by-the-book. You identified a case where a logical modification to the pattern as presented in the book would have helped the application, and that's perfectly fine, especially once you weigh the benefits and costs.