I have a simple MVVM architecture where I’m using a view model to bind commands to a xaml view. My commands are fairly generic and I’ll be binding them to a couple of views so I’ve put them into their own classes implementing the ICommand interface. Inside of the view model I have public accessors like so:
private ICommand _myCommand;
public ICommand MyCommand
{
get
{
if (_myCommand == null)
{
_myCommand = new MyCommand(_injectedModel);
}
return _myCommand ;
}
}
This all works and I’m happy with the architecture but … I have tons of these functions. They all roughly do the same thing – expose the command as a public property, check if a private command already exists and if so use it otherwise create a new command. It’s a bit “boilerplate” for my taste.
I would like a nice way to abstract this. I could create a method that looks up commands based on an identifier from some sort of command map. I could just create all of my commands in the view models constructor (rather than doing so lazily).
What would you consider best practice? Should I avoid instantiating a new command inside each view model and have a central command lookup?
I often do this. The cost of a command is fairly cheap, in most implementations. Depending on your implementation, it’s likely just a small class with a single delegate reference (or a pair of delegate references). This is unlikely to be significant enough overhead, IMO, to warrant the lazy construction.
I often write this as: