Is it worth to write this piece of code:
RelayCommand _saveCommand;
public ICommand SaveCommand
{
get
{
if (_saveCommand == null)
{
_saveCommand = new RelayCommand(this.Save);
}
return _saveCommand;
}
}
instead of just returning new object every time:
public ICommand SaveCommand
{
get { return new RelayCommand(this.Save); }
}
From what I know command getters are used pretty rarely and RelayCommand's constructor is pretty quick. Is it better to write longer code?
I like the null coalescing operator
public ICommand SaveCommand
{
get { return _saveCommand ?? (_saveCommand = new RelayCommand(this.Save); }
}
It returns the left-hand operand if the operand is not null, otherwise it returns the right operand.
This design might be missleading for the users of your class. For example they can read the value of the property in a loop with thousands of iterations. That will create many new objects and the user probably won't expect that.
See the documentation of StyleCop warning CA1819: Properties should not return arrays - this is a very similar issue.
Typically, users will not understand the adverse performance implications of calling such a property. Specifically, they might use the property as an indexed property.
Additionally, SaveCommand == SaveCommand
will be false. I think this is counterintuitive.
To sum up, this might not be the best design, however, if the users of your code know how it works and how to use it properly, then it's ok.
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