Creating Branches with Commands

In the previous article, Creating Composite Commands, we have seen a command composition pattern that is like a sequence. In this article, we are going to explore one resembling to branching. With the combination of the two, complex workflows can be described as reactions to user initiated actions.

CanExecute

The CanExecute method of this command will always return true, so that the condition will be always evaluated for either executing the true or false branch. Because CanExecute is always true, CanExecuteChanged will be never raised, and as a result we are going to get a warning during compilation. This warning, with the code 0067, should be temporarily disabled around CanExecuteChanged. We should always pay attention to what the compiler is saying if we want to write quality code. Another rule regarding quality code is that we don’t disable broadly warnings, there is good reason why they are being raised during compilation. Your task as a software engineer is to make good decisions where to ignore them, or if you should not ignore them, write code that is not raising them.

Constructor

The constructor of this command will take three parameters:

  • A function that has an object parameter, and returns true. This function will be evaluated to make decision about which branch, if any, to execute.
  • One object implementing the ICommand interface to represent the if block of the if-then-else construct, and
  • One object implementing the ICommand interface to represent the else block of the if-then-else construct.

Keep in mind, that having only one object on each branch is not a problem, as we can group actions together with the previously mentioned CompositeCommand. If any of the ICommand objects is null, we will not execute that branch if the condition selects it.

Pretty much this is it for the tricks on building branching into command workflows. You can find the command in my Commands library at https://www.nuget.org/packages/ATZ.Commands/ and you can dive into the source code at https://github.com/atzimler/Commands .

You can connect with me on LinkedIn, Twitter or you can register on the blog. Share if you found this article useful or know somebody who would benefit from reading it.

By subscribing to the email list, you will be notified about new posts.
Loading

 

No comments yet.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Powered by WordPress. Designed by WooThemes