Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I check an ICommand's CanExecute method before calling Execute from procedural code?

When using ICommands in XAML, WPF uses the CanExecute method to enable or disable controls associated with the command. But what if I am calling Execute from procedural code? Should I first check CanExecute to make sure that the command can execute, or should Execute take care of this check for me?

In other words, should I do this:

if (someCommand.CanExecute(parameter, target))
    someCommand.Execute(parameter, target);

Or just this:

someCommand.Execute(parameter, target);
like image 710
Matthew Avatar asked Aug 04 '11 14:08

Matthew


People also ask

Which method of Icommand will let you know if command can be executed or not?

CanExecute will determine whether the command can be executed or not. If it returns false the button will be disabled on the interface.

What is CanExecute?

Defines the method that determines whether the command can execute in its current state. public: bool CanExecute(System::Object ^ parameter); C# Copy.


2 Answers

Good style would dictate that you should do the former, check CanExecute first. This will enforce proper decomposition and a consistency in implementation. Also, in the event you ever do want to use this command bound to a button, it will work as expected.

like image 189
themaestro Avatar answered Oct 23 '22 22:10

themaestro


You should just call Execute and let the command implementation handle validation. CanExecute is mainly provided for UI state bindings.

Except for very simple single-threaded scenarios even if you do call CanExecute first there could easily be a race condition whereby the command validity changes between the CanExecute and the Execute calls, rendering the call to CanExecute pointless.

like image 25
Stu Mackellar Avatar answered Oct 23 '22 22:10

Stu Mackellar