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.
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.
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 .