I'm beginning a project using Xamarin Forms for cross-platform development of a mobile app. I'm using the MVVM model, of which I have little experience of beyond a few small WPF applications.
I'm using the ICommand interface to create commands and binding to them in the view's XAML, which by default involves a good amount of duplicate code. Xamarin.Forms provides a concrete subtype, Command, of ICommand, which is used as in the discussion here, and I see two obvious ways to instantiate them.
Option #1 - Assign the Commands in the constructor.
public class Presenter : ObservableObject
{
public Presenter()
{
DoStuffCommand = new Command(DoStuff);
}
public ICommand DoStuffCommand { get; set; }
private void DoStuff()
{
// VM stuff
}
}
Option #2 - Instantiate Command in the getter
public class Presenter : ObservableObject
{
public ICommand RunCommand { get { return new Command(DoStuff); } }
private void DoStuff()
{
// VM stuff
}
}
Many view models are going to have a number of commands, and approach #2 avoids assigning all of these one by one in the constructor - when the commands action is not going to change, it's clearer to me having this action declared with the ICommand itself. On the other hand, this will create a new instance of Command every time the command fires, which is clearly less efficient memory wise than approach #1.
Does anyone have experience of this, and/or could give me an idea of whether this could impact performance noticeably? And is there a way to improve upon this, such as by manually destroying the Command objects?
Thanks!
An alternative to option #2 would be to have a backing field for it and ensures it only instantiates once:
private ICommand _doStuffCommand;
public ICommand DoStuffCommand =>
_doStuffCommand = _doStuffCommand ?? new Command(DoStuff);
private void DoStuff()
{
}
Related
In the project I'm working on, I've added a base ViewModel class which contains some functionality and dependencies common to all ViewModels. It provides validation, messaging, dispatching and navigation services through the following properties:
IValidateProperties Validator { get; }
IMessenger Messenger { get; }
IDispatcherHelper DispatcherHelper { get; }
INavigationService Navigation { get; }
I use an IoC container to wire my dependencies, however I have a few options for how to handle these dependencies which are common to all of my ViewModels:
Inject them in the constructor. If I did this, then it would require adding these four arguments to the constructor of every single ViewModel and pass them to the base constructor. That's a lot of extra noise added to my code base, which I'd really rather avoid. Also, if I were to add another dependency at some point, that would require changing the constructor of every single ViewModel.
Use property injection. This is the approach I'm working with now. Unfortunately, it means not being able to access these properties until after the ViewModel has been constructed, resulting in the following workarounds:
private IValidateProperties _validator;
public IValidateProperties Validator
{
get => _validator;
set
{
_validator = value;
_validator.ValidationTarget = this;
}
}
private IMessenger _messenger;
public IMessenger Messenger
{
get => _messenger;
set
{
_messenger = value;
MessengerAttached();
}
}
protected virtual void MessengerAttached() { }
Make the properties static and inject them on app startup. This is easy for Messenger, DispatcherHelper and Navigation because they are used as singletons anyway. For Validator, I would need to add a static ValidatorFactory, and instantiate the Validator in the constructor using the factory. This way seems to be the cleanest way to do things, but I have this voice in the back of my head telling me that using statics like this is a bad idea.
I feel like option 1 is out of the question because of the large amount of noisy boilerplate code it would result in being added to my ViewModels. I'm still unsure whether 2 or 3 is the best way to go though. Is there a good reason that using statics is a bad idea in this case, or am I fretting over nothing?
Some people argue that statics lead to untestable code, but in this case it would actually make things easier to test. If I were to go with option 3, I could add the following class for all of my view model tests to inherit:
public abstract class ViewModelTestBase
{
protected readonly IValidateProperties ValidatorMock;
protected readonly IMessenger MessengerMock;
protected readonly IDispatcherHelper DispatcherHelperMock;
protected readonly INavigationService NavigationMock;
protected ViewModelTestBase()
{
ValidatorMock = Substitute.For<IValidateProperties>();
ViewModelBase.Validator = ValidatorMock;
MessengerMock = Substitute.For<IMessenger>();
ViewModelBase.Messenger = MessengerMock;
DispatcherHelperMock = Substitute.For<IDispatcherHelper>();
ViewModelBase.DispatcherHelper = DispatcherHelperMock;
NavigationMock = Substitute.For<INavigationService>();
ViewModelBase.Navigation = NavigationMock;
}
}
So, what concrete reasons are there for not going with approach #3? And if statics really are such a bad idea in this case, what concrete reasons are there for not going with approach #2 instead?
I'm writing a WPF application using MVVM. My ViewModels are quite large and have a lot of logic associated with them (filtering, searching, writing to the database, etc), so I've decided to try to separate out the logic of the ViewModels to a "Presenter" class like is used in MVP.
So, my basic setup is this:
public class FooViewModel : ViewModelBase, IFooViewModel
{
private IFooPresenter presenter;
private ObservableCollection<FooModel> fooCollection;
public FooViewModel()
{
presenter = FooPresenter(this);
}
public ObservableCollection<FooModel> FooCollection
{
get { return fooCollection; }
set
{
fooCollection = value;
OnPropertyChanged("FooCollection");
}
}
public void FooCommandMethod(object obj)
{
presenter.DoStuff();
}
}
public class FooPresenter : IFooPresenter
{
private IFooViewModel viewModel;
public FooPresenter(IFooViewModel viewModel)
{
this.viewModel = viewModel;
}
public void DoStuff()
{
viewModel.FooCollection.Add(new FooModel());
//etc etc, make whatever ViewModel updates are needed
}
}
I feel like it is bad practice to have this circular dependency (View Model depends on Presenter and Presenter depends on View Model). These classes could be combined into one large ViewModel class, but I do like how clean this approach keeps my View Models, all that they do is hold commands that call presenter functions and hold the Model/collections of the Model. I also dislike the dependency of the ViewModel on the concrete implementation of the Presenter. One approach I have toyed with is using a Service Locator type class, so it would look like this:
public FooViewModel()
{
presenter = PresenterLocator.GetPresenter<IFooPresenter>(this);
}
What I would prefer, though, is to use Constructor Dependency Injection to inject the controller when I create the ViewModel. The problem with this is that this creates a circular dependency in the constructors of the ViewModels and Presenters, which causes my application to crash when I attempt to achieve this using Unity. It ends up looking like this:
public FooViewModel(IFooPresenter presenter)
{
this.presenter = presenterl
}
And
public FooPresenter(IFooViewModel viewModel(
{
this.viewModel = viewModel;
}
So, my concern is that my design approach is inherently flawed due to this. Nevertheless, I really like how clean it keeps my ViewModels and separates them from Business Logic. Is there a better way I could be designing this? Is there any way I can use DI to achieve this? Or by doing that am I essentially trying to force a DI container to act as a Service Locator?
First of all, I would not call this a "presenter". This introduces an unwanted confusion, in fact your presenter doesn't present anything, it is just an extracted bit of code from a large view model. Have you considered calling it just "a service"? A SearchService for example?
Another question is: does such service always depend on a view model? Or rather, could it depend on lower layers (unit of works/repos for example) or other services? Note that because your service depends on a view model and you pass a view model directly there, you loose a control of what happens to the view model inside a service. Your DoStuff method is a perfect example, it does something to a view model, alters its state. Instead, you could have
public class FooViewModel : ViewModelBase, IFooViewModel
{
private IFooService service;
private ObservableCollection<FooModel> fooCollection;
public FooViewModel()
{
service = FooService(this);
}
public void FooCommandMethod(object obj)
{
// the responsibility on consuming service outcome is still here!
this.FooCollection.Add( service.CreateNewModel() );
}
}
public class FooService : IFooService
{
// constructor parameter not needed now
public FooService()
{
this.viewModel = viewModel;
}
public FooModel CreateModel()
{
return ...;
}
}
If you still insist however on having a circular dependency, make it so that one of the two has a parameterless constructor and a property injector:
public class FooViewModel : IFooViewModel
{
private IFooService _service;
public FooViewModel( IFooService service )
{
this._service = service;
this._service.Model = this;
}
}
public class FooService : IFooService
{
public IFooViewModel Model { get; set; }
}
This way Unity asked for a IFooViewModel will resolve a parameterless IFooService and then execute the constructor that sets the cycle for both parties.
This is more of a theoretical question, but I was wondering what's the best way to pass information within forms. I'll explain my issue:
I have my Mainform class which manages the whole application:
public class Mainform : Form
{
private static AddressBook _addressbook = new AddressBook();
private static TemplateManager _templateManager = new TemplateManager();
/*...*/
}
Furthermore, I have another class which is created by Mainform:
public partial class TemplateLists : Form
{
//To be filled with Mainform's information.
private List<Template> _genericTemplates;
private Client _clientToFill;
//In this case, I decided to pass the information through the constructor.
public TemplateLists(List<Template> genericTemplates, Client client)
{
InitializeComponent();
_genericTemplates = genericTemplates;
_clientToFill = client;
}
}
The issue is that, in order for TemplateLists to recieve the _genericTemplates information, I don't know if it's best done through the constructor, a method or public properties and why. In any case, I know how to implement them all, but I don't know which is best and I don't have any reasons to pick one over another.
Basically your whole question can be brought down to when should one use constructor (ctor) parameters vs properties.
Constructor parameters:
These should be used to set mandatory values on your instance. In other words these are the values without which your class instance cannot function.
Class properties:
These should be used when the values are optional for your object's functioning.
Consider an example, wherein your class pulls data via a service (which in turn talks to database etc). Also you intend to perform some sort of logging. In this case, you know that your class will not work without a service instance but you logging can be optional for this class. So while instantiating StoreManager you have option to set logger if you wish.
public class StoreManager
{
private readonly IService dataService;
public StoreManager(IService dataService)
{
if(dataService == null)
{
// Do not allow to go further.
throw new ArgumentException();
}
this.dataService = dataService;
}
public ILogger Logger
{
get;
set;
}
public IList<Product> GetProducts()
{
var products = dataService.GetProducts();
// logging is optional
if(Logger != null) {
Logger.Trace("Products fetched {0}", products.Count);
}
}
}
Better to use Dependency Injection or Service Location. Check this and this for reference.
There is no such thing as "the best" solution. It really comes down to how the form is used. For example it depends what the generic templates are. If they are necessary for the form to be created, it's a good idea to pass it via constructor to prevent that the form is instanciated incomplete.
If they are optional you could assign the after the form is created.
The implementation details (dependency injection, concrete coupling, etc.) depends on how the form is going to be used.
After a major edit to this quesiton, I'm hoping it's now clear.
I'm very lost with binding in WPF when 1 change should affect multiple properties.
I regularly use VVM to bind my ViewModel to my View and I would say I'm OK with it.
I am trying to implement a state controller. This means that, what ever settings I made in part of my UI, the reflection is through out.
For example in my part of my UI, I can toggle a feature on or off, such as "show images"
When I make this change, I'd like everything in my application to be notified and act accordingly.
So, my StateController class will have a property
public bool ShowImages
And in my View, I'd likely have something like
<image Visible ="{Binding ShowImages", Converter={StaticConverter ConvertMe}}" />
The problem I have is how I go about making the StateController alert all of my ViewModels of this.
Currently, in each ViewModel I'm assuming I'd have to have the same property repeated
public bool ShowImages
EG
public class StateController : BaseViewModel
{
public bool ShowImages{get;set;}//imagine the implementation is here
}
public class ViewModelB : BaseViewModel
{
public bool ShowImages{}//imagine the implementation is here
}
public class ViewModelB : BaseViewModel
{
public bool ShowImages{}//imagine the implementation is here
}
So, my question is, if I updated ViewModelB.ShowImages, how would I first inform the StateController which in turn updates all ViewModels.
Is this something the INotifyPropertyChanged can do automatically for me since they all share the same propertyName, or do I have to implement the logic manually, eg
public static class StateController
{
public bool ShowImages{get;set;}//imagine the implementation is here
}
public class ViewModelA : BaseViewModel
{
public bool ShowImages
{
get { return StateController.ShowImages; }
set { StateControllerShowImages = value;
OnPropertyChanged("ShowImages"); }
}
}
public class ViewModelB : BaseViewModel
{
public bool ShowImages
{
get { return StateController.ShowImages; }
set { StateControllerShowImages = value;
OnPropertyChanged("ShowImages"); }
}
}
I hate the idea of the above implementation but it does show what I'm trying to achieve. I just hope there is a better way!
The PropertyChange notification is only raised for that one object model.
So raising a change notification of the "Name" property of ClassA will only update the UI in cases where it's bound to that specific ClassA.Name. It won't trigger a change notification for any ClassB.Name, or other instances of ClassA.Name.
I would suggest using a Singleton here for your StateModel, and having your other models subscribe to the StateModel.PropertyChanged event to know if it should update, like this answer.
public ViewModelA
{
public ViewModelA()
{
StateController.Instance.PropertyChanged += StateController_PropertyChanged;
}
void StateController_PropertyChanged(object sender, NotifyPropertyChangedEventArgs e)
{
// if singleton's ShowImages property changed, raise change
// notification for this class's ShowImages property too
if (e.PropertyName == "ShowImages")
OnPropertyChanged("ShowImages");
}
public bool ShowImages
{
get { return StateController.Instance.ShowImages; }
set { StateController.Instance.ShowImages = value; }
}
}
If I understood you correctly, you are looking for a mechanism that allows your different ViewModels to communicate between each other.
One possible way would be to implement the Observer Pattern (a code example can be found here: "Observer pattern with C# 4"). In this way your ViewModel subscribe each other to receive change notifications from a "publisher", i.e. the ViewModel that had its value changed. You have a good control over who receives which notification from which publisher. The downside of this approach is a tight coupling between your models.
My approach would be this:
Use a message dispatcher. Your ViewModels can subscribe to a certain type of message, e.g. ShowImagesChanged. If any of your ViewModels changed the ShowImages property, that ViewModel calls the dispatcher to send out such a ShowImagesChanged message with your current values.
This way you can keep you ViewModels decoupled from each other. Still, although the ViewModels do not know each other this gives a way to exchange data between them.
Personally, I have used the Caliburn Micro MVVM framework several times for this, but there should be enough other MVVM frameworks that provide the same functionality to fit your taste.
The Calibiurn Micro documentation and how easily the dispatcher can be used is here: Event Aggregator
To avoid code repetition you can create a class derived from BaseViewModel that implements your property and have ViewModelA, ViewModelB extend it. However, this does not solve the problem of keeping each instance updated.
In order to do so, you may:
Use a static class (your current solution) or a Singleton as suggested in one of the comments. This is simple but has potential problems such as race conditions and coupling.
Have your ShowImages binding property repeated in each ViewModel and update it by subscribing to a ShowImagesChanged event. This could be published through a Command executed from the UI. I'd say this is the WPF approach and has the benefit of decoupling the ShowImages state management from its consumption.
Assign the ShowImagesupdate responsibility to a single ViewModel and subscribe to the its PropertyChanged in the other ViewModels so that they update accordingly. Better than the first option, but still huge coupling.
Why repeat properties at all? Just bind to StateController itself.
Say we have singleton StateController:
public class StateController : INotifyPropertyChanged
{
private static StateController instance;
public static StateController Instance {
get { return instance ?? (instance = new StateController()); }
}
//here`s our flag
private bool isSomething;
public bool IsSomething
{
get { return isSomething; }
set
{
isSomething = value;
PropertyChanged(this, new PropertyChangedEventArgs("IsSomething"));
}
}
private StateController(){}
public event PropertyChangedEventHandler PropertyChanged = delegate { };
}
Then in base VM class just make a reference to this controller:
public StateController Controller { get { return StateController.Instance; } }
And where needed bind like this:
<CheckBox IsChecked="{Binding Controller.IsSomething}">
Test
</CheckBox>
This way every binding will work with one property and react to one property. If you need some custom code to work you can subscribe to PropertyChanged of StateController where needed and take action.
I'm currently implementing the Command-Handler Pattern for a service I'm designing where the Command is essentially a DTO for the Handler's .Handle() method. As I begin to implement various concrete classes I realize that in order to satisfy the Open/Closed Principle and Single Responsibility Principle I may end up with thousands of Command and Handler classes, which would significantly violate the Don't Repeat Yourself Principle.
For example, part of the process I'm encapsulating requires deleting all data by ProjectId from 60 odd tables to reset them. If I implement each one as an atomic concrete Command object and concrete CommandHandler object then I'll have 120 classes just for this first step. They will all perfectly follow SRP & OCP, however DRY takes a serious beating...
public class DeleteProjectLogCommand : CommandBase
{
public long? ProjectId { get; set; }
}
public class DeleteProjectLogCommandHandler : ICommandHandler<DeleteProjectLogCommand>
{
public async Task<Feedback<DeleteProjectLogCommand>> Handle(DeleteProjectLogCommand command, CancellationToken token)
{
// ...
}
}
Alternatively I could implement a single, multipurpose, command and handler class and a ProjectTables enumeration could be used in place of all the discrete classes.
public class DeleteTableByProjectIdCommand : CommandBase
{
public DeleteTableByProjectIdCommand(ProjectTables table, long? projectId) {}
public long? ProjectId { get; set; }
public ProjectTables Table { get; set; }
}
public class DeleteTableByProjectIdCommandHandler : ICommandHandler<DeleteTableByProjectIdCommand>
{
public async Task<Feedback<DeleteTableByProjectIdCommand>> Handle(DeleteTableByProjectIdCommand command, CancellationToken token)
{
switch(command.Table)
{
case ProjectTables.ProjectLog:
// x60 tables
break;
}
}
}
However this would violate the Open/Closed Principle because if a new table is added, both the enumeration and every place that uses it, would have to be updated as well. Not to mention the smell you get from a 60-case switch statement.
Sooo... who wins? DRY or SRP & OCP?
Don't get too tied up with acronyms. Concentrate on writing code that feels right. Atomic commands are a very good idea, but you need the right level of granularity I generally consider a command to be a complete (user) operation.
Your design of an enum and a God switch fails a basic sanity test and is not extensible without modifying the class itself, so it must be bad, right?
Consider using a RelayCommand: http://msdn.microsoft.com/en-us/magazine/dn237302.aspx
This is a command that implements ICommand, but expects to have a delegate injected for the actual work. A number of MVVM frameworks include a RelayCommand (or DelegateCommand) out of the box.
So, you implement your command interface, and demand that an Action, or an Action<T> be injected in the ctor. Execute triggers the action. If you need to pass something to the action, you can use the "ofT" version, or enclose it in the delegate that you pass.
This allows you to:
Have a single implementation of Command (or 2, if you support a generic)
Put the actual command logic somewhere else (like in your domain object)
If it makes sense, the command logic can actually be a Private member of your domain class, exposed by the command because you passed the delegate.
Example:
public class SomeViewModelOrDomainClass
{
public ICommand DoItCommand {get; private set;}
//ctor
public SomeViewModelOrDomainClass()
{
// if your command includes a CanExecute bool, then also demand a Predicate to handle CanExecute
this.DoItCommand = new RelayCommand(() => this.SomePrivateMethod(maybeEvenAnEnclosedParam), aCanExecutePredicate);
}
}
Hundreds of commands and handlers don't violate DRY neither OCP, because a command contains an order for a specific use case i.e each command and handler are implementing a business use case. Do you have identical business use cases?
An example, I worked on an app which has different resource types. But I had only 1 DeleteCommand which looked like this
public class DeleteResource:AbstractCommand
{
public Guid ResourceId;
public ResourceType Type;
}
public class DeleteResourceHandler:IExecute<DeleteResource>
{
private IDispatchMessages _bus;
private IStoreResources _repo;
public DeleteResourceHandler(IStoreResources repo, IDispatchMessages bus)
{
_repo = repo;
_bus = bus;
}
public void Execute(DeleteResource cmd)
{
_repo.Delete(cmd.ResourceId);
var evnt = cmd.ToEvent();
_bus.Publish(evnt);
}
}
Of course this is not the whole story, because the whole app was designed to work with N resource types and this means my entity storage was mainly a key-value store which didn't care about entity structure. Delete just needs an id.
Once the resource was deleted en event is published which is handled by the read model updater which then deletes the query data for that resource type.
When adding a new resource, I don't need to touch the DeleteCommand or the DeleteHandler nor even the entity storage. But you see, the command and handler don't work alone, they're using other components which allows them to achieve DRY and OCP. And OCP is a bit fuzzy principle.