Should I use the Command pattern instead of a call to a static method?

851 views Asked by At

With the hope of learning the Command pattern, I have set up a simple GUI application in C# with two buttons. The first button uses (my attempt at) the Command pattern to perform an operation, whereas the second simply calls a static method in another class.

Here is the form code

    private void CommandButton_Click(object sender, EventArgs e)
    {
        ICommand command = new ConcreteCommand();
        command.Execute(); //Performs the same code as DoOperation()
    }

    private void StaticButton_Click(object sender, EventArgs e)
    {
        Helper.DoOperation(); //Performs the same code as Execute()
    }

My questions are:

  1. Is it appropriate to to implement the Command Pattern in this scenario?
  2. What advantages/disadvantages are associated with using the Command Pattern over static method calls in this specific case? In other, "real world" scenarios?
  3. If my GUI design changes in the future, would it be any more difficult or would it imply more changes to existing code if I used static function calls instead of the Command Pattern?
2

There are 2 answers

2
Vinay Pandey On BEST ANSWER

Command Pattern is used to do set of operations based on the value in command argument, whereas in the code you have shown there is no dependency on the current state. In your case I static method would be fine.

But this wont always be the case so study well your need and then opt for the way to proceed, I would have gone for Command Pattern as this gives more flexibility with future change to requirement.

0
Euphoric On

There is no real advantage of using command pattern in your case. Also, your implementation is incorrect. With command pattern, the one who creates the command is different from one who executes the command. This difference allows you do do some interesting stuff like giving someone else ability to execute the command.

For example, commands are natural part of WPF. There, you can DataBind the command object to the button and leave the actual execution to the button. No need for events or such. Unlike your case, where you have to use events (assuming you are using WinForms)