I want to issue a series of Command executions, but only when the prior command succeeded. Right now i am raising an event within the command object indicating whether the command succeeded or failed. I am using this to control execution, but it feels inelegant.
Example:
command1.CommandSucceeded += delegate { command2.Execute(); };
command1.Execute();
This works, but it feels clumsy and unintuitive. I could pass a boolean back on Execute() indicating success or failure, but that is along the same path. I could throw exceptions on failure, which would might result in cleaner code, but might be overkill.
Any suggestions?
I got around this by setting up a command "chain". I created a Command object that holds other commands, then fire each of them in turn when Do is called. In your case, you could have the command call the delegate and only fire off the next command in the sequence if it was successful.
One way to do it, I suppose.
Returning a boolean or an object representing some status is not that bad. It might be feel clumsy, but it's simple and clear.
One implementation I use is something like this:
First I add the Command objects into a list.
List<ICommand> commands = new List<ICommand>;
commands.Add(command1);
commands.Add(command2);
Then the list of Command objects gets executed like this:
foreach (ICommand command in commands)
{
bool success = command.Execute();
if (!success) break;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With