C# Command Design Patter Class Question

I am following the code in the below example.  For the most part it fits my needs.

http://www.dotnet-tricks.com/Tutorial/designpatterns/23JE110913-Command-Design-Pattern---C

All of my commands need to execute.  However two commands actually needs to return different values.  Is there a way to modify the pattern so I can return values for these two commands but leave the other commands executing as is?

Thanks
LVL 2
CipherISAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Kyle AbrahamsSenior .Net DeveloperCommented:
If I understand you correctly you may want to do an integer or an enum type of value . . . then you can set that in the execute and return whatever value you needed.

If you showed your code and what you were trying to do it would be helpful.
Daniel Van Der WerkenIndependent ConsultantCommented:
There are probably a couple of ways to do this -- if I understand what you want to do correctly.

Option 1: Create an object, you populate this object when the command executes, and then populate part of the object that's appropriate to the information you want returned and return the whole object.

Option 2: Return a Tuple<type1, type2> where you are, again, populating the type appropriately.

On the receiving end, you'll need to know what you're looking for. So, example:

public class MyInfoObject
{
     public  int MyNumberOfThingiesDone;
     public string MyReallyCoolInfo;
}

Open in new window

then
public interface ICommand
{
      MyInfoClass Execute();
}

Open in new window

Something like:
public class FlipDownCommand : ICommand
{
 private Light _light;
 
 public FlipDownCommand(Light light)
 {
 _light = light;
 }
 
 public MyInfoClass Execute()
 {
     MyInfoClass infoClass = new MyInfoClass();
     infoClass.MyNumberOfThingiesDone = 101;
     infoClass.MyReallyCoolInfo = string.Empty;
     _light.TurnOff();
     return infoClass;
 }
}

Open in new window

public class FlipUpCommand : ICommand
{
 private Light _light;
 
 public FlipUpCommand(Light light)
 {
 _light = light;
 }
 
 public MyInfoClass Execute()
 {
     MyInfoClass infoClass = new MyInfoClass();
     infoClass.MyNumberOfThingiesDone = int.MinValue;
     infoClass.MyReallyCoolInfo = "Kittens are cute."
     _light.TurnOn();
     return infoClass;
 }
}

Open in new window


And also:
public class Switch
{
 private List<ICommand> _commands = new List<ICommand>();
 
 public MyInfoClass StoreAndExecute(ICommand command)
 {
      _commands.Add(command);
      return command.Execute();
 }
}

Open in new window

then in use:
 if (cmd == "ON")
 {
   string infoINeed = s.StoreAndExecute(switchUp);
 }
 else if (cmd == "OFF")
 {
   int InfoNumbers = s.StoreAndExecute(switchDown);
 }
 else
 {
 Console.WriteLine("Command \"ON\" or \"OFF\" is required.");
 }

Open in new window


The Tuple implementation would be similar.

Does this help?
kaufmed   ( ⚆ _ ⚆ )I asked the operating system what I could do to become a better programmer. It said, "Let me give you some pointers."Commented:
While Tuple would work functionally, semantically you would be doing a disservice to other developers reading your code. With a Tuple, you get properties such as Item1, Item2, Item3, etc. There's no meaning behind those names. The meaning is in the value itself. I would lean more towards the custom class, or possibly a generic implementation of your command classes.
Jeevan BordoloiCommented:
If you want to keep your interface consistent, modify the return type of the Execute method from void to a generic return type - may be you can create a new type.

I have modified my previous example (http://www.experts-exchange.com/questions/28926412/C-Write-a-class-checking-for-commands.html) to
(1) Change the return type of the ICommand.Execute method to return a generic type "CommandExecutionResult".
(2) Create a new type called "CommandExecutionResult", which just wraps around a Point.
(3) Add a static property called "Empty" in the new "CommandExecutionResult" class, which returns a CommandExecutionResult with default/empty values (semantically here I am assuming that an empty/default point means (0,0) - which doesn't make much sense in reality).
(4) All concrete implementations of commands except the newly introduced "GetDiagonallyOppositPointCommand" returns a CommandExecutionResult.Empty from its Execute method after "performing the action".
(5) The newly implemented "GetDiagonallyOppositPointCommand" returns a CommandExecutionResult which contains a Point which is diagonally opposite to the "receiver" point.
(6) Invoker class now has a property called Result of type "CommandExecutionResult".

Check if this meets your needs:


using System;

namespace CommandsExample
{
    class Program
    {
        static void Main(string[] args)
        {
            Point p = new Point
            {
                X = 2,
                Y = -5
            };
                        
            Invoker invoker = new Invoker(p);

            // Execute "Up"
            ICommand command = new UpCommand();
            invoker.SetCommand(command);
            invoker.ExecuteCommand();
            Console.WriteLine("X = {0}, Y = {1}", p.X, p.Y);

            // Execute "Left"
            command = new LeftCommand();
            invoker.SetCommand(command);
            invoker.ExecuteCommand();
            Console.WriteLine("X = {0}, Y = {1}", p.X, p.Y);

            // Execute "Down"
            command = new DownCommand();
            invoker.SetCommand(command);
            invoker.ExecuteCommand();
            Console.WriteLine("X = {0}, Y = {1}", p.X, p.Y);

            // Execute "Right"
            command = new RightCommand();
            invoker.SetCommand(command);
            invoker.ExecuteCommand();
            Console.WriteLine("X = {0}, Y = {1}", p.X, p.Y);

            // Get the diagonally opposite point
            command = new GetDiagonallyOppositPointCommand();
            invoker.SetCommand(command);
            invoker.ExecuteCommand();
            Console.WriteLine("X = {0}, Y = {1}", invoker.Result.Value.X, invoker.Result.Value.Y);

            Console.ReadKey();
        }
    }

    class Point
    {
        public int X { get; set; }
        public int Y { get; set; }


    }

    interface ICommand
    {
        CommandExecutionResult Execute(Point p);
    }

    class UpCommand : ICommand
    {
        public CommandExecutionResult Execute(Point p)
        {
            p.Y++;
            return CommandExecutionResult.Empty;
        }
    }

    class DownCommand : ICommand
    {
        public CommandExecutionResult Execute(Point p)
        {
            p.Y--;
            return CommandExecutionResult.Empty;
        }
    }

    class LeftCommand : ICommand
    {
        public CommandExecutionResult Execute(Point p)
        {
            p.X--;
            return CommandExecutionResult.Empty;
        }
    }

    class RightCommand : ICommand
    {
        public CommandExecutionResult Execute(Point p)
        {
            p.X++;
            return CommandExecutionResult.Empty;
        }
    }

    class GetDiagonallyOppositPointCommand : ICommand
    {
        public CommandExecutionResult Execute(Point p)
        {
            return new CommandExecutionResult
            {
                Value = new Point
                {
                    X = -1 * p.X,
                    Y = -1 * p.Y
                }
            };
        }
    }

    class Invoker
    {
        private Point _point;
        private ICommand _command;
        public CommandExecutionResult Result { get; private set; }

        public Invoker(Point point)
        {
            _point = point;
        }

        public void SetCommand(ICommand command)
        {
            _command = command;
        }

        public void ExecuteCommand()
        {
            Result = _command.Execute(_point);
        }
    }

    class CommandExecutionResult
    {
        public static CommandExecutionResult Empty
        {
            get
            {
                return new CommandExecutionResult
                {
                    Value = new Point
                    {
                        X = 0, Y = 0
                    }
                };
            }
        }

        public Point Value { get; set; }
    }
}

Open in new window

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C#

From novice to tech pro — start learning today.