GWT, MVP, and UIBinding - How to get the best of all worlds - gwt

With MVP, you normally bind the View (UI) with the Presenter in the Presenter. However with the latest version of GWT, especially with UIBinding, you can do the following in the View:
#UiHandler("loginButton")
void onAboutClicked(ClickEvent event)
{
// my login code
}
Which basically exchanges a lot of anonymous inner class code for some quick annotation code. Very nice!! The problem is that this code is in the view and not the presenter...
So I thought maybe:
#UiHandler("loginButton")
void onAboutClicked(ClickEvent event)
{
myPresenter.onAboutClicked(...);
}
But there are several problems with this approach. The most important, you blur the lines between View and Presenter. Who does which binding, in some cases it's the View, in others it's the presenter (binding to events not in your current view but that need to be attached - for example a system wide update event).
You still get the benefit of being able to unit test your presenter, but at what cost. The responsibilities are messy now. For example the binding is sometimes in the View and others times in the Presenter level. I can see the code falling into all kinds of chaos with time.
I also thought of extending the Presenter to the View, so that you could do this in the View. The problem here is that you lose the Presenter's ability to run standard unit tests! That's a major issue. That and the lines again become blurred.
So my question, does anyone have a good method of taking advantage of the annotation from UIBinding within the MVP pattern without blurring the lines and losing the advantages of the MVP pattern?

I tend to use the #UiHandler approach only when the Handler does view-specific stuff, like adding style names, etc. For other purposes (adding validation, etc), I stick with the old approach of adding the appropriate Handlers in the Presenter.
I'd recommend reading through one of the many threads on GWT Google Group about MVP and UiBinder, such as this one.

To be honest I don't use the #UiHandler annotation much, because as you said, it starts to muddy the lines between the View and the Presenter. It's totally fine to use, and a great shortcut if you don't particularly care about sticking to the pattern, though.
The presenter.onAboutClicked() route is definitely an option, but then you might as well define the handler in the presenter in the first place.

or if you are looking for a real implementation on how to make it work check out this blog post, I have to say that up until I found it everything else was still noise in my learning.
gwt 2.0.x is a great improvement on gwt 1.x but I still believe google has some way to go with their documentation and guidance since as we have seen with uibinder and mvp, it leaves a lot to the imagination on how to make things work.
hope the link shades a little bit more light on what u need.

If using the MVP pattern, your SomeView interface should have an inner Presenter interface defined which in turn in implemented by your presenter (Activity class). So inside the view do the following:
interface SomeView extends IsWidget
public interface Presenter{
...all the methods
public void doSomeAction(SomeView view);
}
...view methods
}
now in the SomeViewImpl class, attach a handler
#UiHandler("some_button")
void onClickSomeButton(ClickEvent e){
// call the presenter method (you have access to it in the ViewImpl class
presenter.doSomeAction(this);
}
It looks a bit long, but the pattern works great.

It's often useful for the view to delegate some of its actions to the presenter using a pattern sometimes referred to as a "supervising controller".
This has also been advocated by Google as a good way to benefit from the nice #UiHandler annotation at your disposal when you use !UiBinder. The main difference with the original presenter pattern is that the view keeps a link back to the presenter in order to invoke some of its methods, instead of the presenter registering callbacks towards the view.
https://github.com/ArcBees/GWTP/wiki/UiHandlers

Related

How to pass a View to my ViewModel so an I*Service can use that View to do something

https://github.com/brianchance/MvvmCross-UserInteraction is a very nice plugin for showing cross platform Alerts!
But for this question, can we assume it can not use a UIAlertView (or some other top level MessageBox type call on other platforms) but needs to show a Message within a given subsection of the screen (i.e. on IPhone you would need to supply a UIView to the plugin which it will use to show the message within).
So, how would you set this up so the ViewModel knows what View to use as its display container?
As a specific example, if I wanted an Error Service, as so -
public interface IErrorPFService
{
void Show();
void Hide();
void SetErrors(List<Error> errors);
}
and I create a platform specific implementation for it.
If I inject this into my ViewModel so it can control Error Show/Hide/Set how do I tell it the UIView (or equivalent) that I want my Errors to show within?
Can I just expose the IErrorPFService field as a public property and do -
MyViewModel.ErrorPFService = new ErrorPFService(View);
in my ViewDidLoad ...
Or is this coupled incorrectly vs Mvvm Practice?
I would expect the ViewModel to subscribe itself to the ErrorService.
When receiving a message it would expose it in a collection(?) and the View would bind to that collection.
This way the View is unknown to the service and the ViewModel has the chance to influence the View contrary to your solution.
It would help if you could give an example for the scenario you are describing.
Sometimes, the way you visually want to display something might not be the best way, so if it's possible for you, you might find a different and simpler way, which spares you from having to find a solution regarding what you are describing.
Generally, I always do the best I can to avoid the idea of having to actually pass a 'view' or an abstraction of it, from the view-model to view. Also, cross-platform wise, things can work very different in terms of UI interaction. You can find yourself in a situation when things are complicated just because UI works differently than what you expected.
But let's try find another perspective:
At any given point, the view knows what data \ feature it's displaying. So when you are calling from the view-model an user interaction action (by a service, property change, event, etc) the view should 'expect' it.
For example, the platform specific user interaction implementation is able to get the currently displayed top-view and interact it in a platform specific manner or based a relationship. In your example, the message-box can be displayed in a specific sub-view of the top level view.
In advanced scenarios, I guess you could try to create a cross-platform approach for this, but you should try to put in balance all the abstraction you want to create just for that. Think about doing this as a plan ... Z. If possible. Again, giving an example might help.

GWT: MVP Presenter Interface

I try to understand how the gwt example about activities and places works (https://developers.google.com/web-toolkit/doc/latest/DevGuideMvpActivitiesAndPlaces). I am wondering why they define an interface for the presenter. I know the view interface is helpful to exchange the view easily. But what's the use of the presenter interface?
Its always a best practice to design application with interfaces rather than concrete classes.
Reference - What does "program to interfaces, not implementations" mean?
Reference - WikiPedia example for MVP
Another key factor in MVP architecture to make your design pretty clean is defining an Presenter interface(As we already know the beauty of interface OOP conceptin JAVA).
Presenter interface that allows our View to callback into the presenter when it receives an event. The Presenter interface defines the following:
public interface Presenter<T> {
void onAddButtonClicked();
}
And then you can set the presenter to your view like below
private Presenter<T> presenter;
public void setPresenter(Presenter<T> presenter) {
this.presenter = presenter;
}
Finally when your PresenterConcreteClass implements your presenter interface those implementations will triggers.
Besides the cleanliness of using an interface, there's also no reason you wouldn't test your view. You could use end-to-end tests, but you can also simply use a GWTTestCase where you instantiate the view and use a mock presenter.
You'd then be able to test that “when I click on this button, it should call this method from the presenter with the values X, Y and Z as arguments”, or “when I call this method of the view with those arguments, then such widget should turn red and that other one should hide/collapse/show/whatever”.
I've also used it, once, to similarly build a simple testbed app to manually test the UI with fake data. The app consisted of buttons to simulate the presenter calling the view with fake data, and handled the presenter calls back from the view with Window.alert or similar things. You'd launch the app in your browser and click here and there and validate that the view works as expected.
This can be useful when you later add a field to your form, to make sure you correctly wire it with the presenter. You don't want to setup your GWT-RPC/RequestFactory/whatever services from the real presenter, when a unit-test could be enough.
2 big reasons off the top of my head (there may be others too...)
Testing: Your Presenter then does not have to have a direct reference to the View, which is nice because the View contains GWT Objects (i.e: any Widget) which cannot be used in a standard Unit Test Case: Any GWT Object must have a JS container (i.e: Browser, or GWTTestCase) to be instantiated; A JUnit test case cannot use a Browser; GWTTestCase runs VERY slow, so you should prefer not to have to use it. Without the interface, the Presenter would have to reference the View's methods by a direct reference to the View; that means when testing the Presenter, you must instantiate the View, which must instantiate its Widgets (which at that point require the GWTTestCase for the Widgets). And all you should be aiming to do in the 1st place is to test the logic, which should be completely in the Presenter to avoid GWTTestCase... With the Display interface, you can do just that: Focus on testing the Presenter, without the complication of instantiating the View (which has its own degree of instantation complication) and messing around then necessarily with GWTTestCase
Have multiple Views for the same Presenter: [I think you would only ever do this if you have different platforms (i.e: mobile App vs. browser) which each require their own View (since a mobile App version of the View is rendered differently from a browser View, since they are different platforms with different GUI entities)]. The multiple Views would then all just implement the Display interface in their separate ways. Then the single Presenter can contain the logic that is the same for all Views, be used for all the different Views, and all View implementations are guaranteed to follow the same expectations (which are the codification in the Display interface) of that single Presenter! This is a manifestation of the OOP best practice of designing with interfaces, which #SSR Answers.

GWT MVP composition of parts

We've been using the recommended GWT approach of building parts of our application in an MVP manner. The logic we use is based on Google's examples - the Presenter fetches/prepares data and sets it on the View, and the View contains a reference to the Presenter which it calls (e.g. in UiHandlers).
Some parts of the application which we built should be reused in other views. For example - a view which is sometimes the "main view" of a part of the application - can be used inside a pop-up in another part of the application (of course, the views/presenters are initialized differently in this other case, but basically it is the same thing).
What would be the correct approach to do stuff like this? I cannot seem to find a suitable one without resorting to ugly hacky stuff.
For example - if I put the presenter of the reused component inside the main view - it is easy to initialize the reused component, but it is ugly to receive a result back in the main presenter. This can be solved by passing a runnable or creating a custom handler or passing the parent presenter itself to the reused presenter.
All of these approaches don't seem right to me though and seem ugly.
Any ideas/experiences?
What you're describing is a view being able to be controlled by 2 distinct presenters. Abstracting those presenters behind a common API, in the form of an interface, should be enough.
You can also see it as a composite widget being used within two distinct views. The composite widget would then expose events and a public API that both views could wire to their specific presenters.
See Activites and Places,It can help you to desing and structure you app.
https://developers.google.com/web-toolkit/doc/latest/DevGuideMvpActivitiesAndPlaces
.

Opening save file dialog in MVVM using OnPropertyChange is Ok or Not

I am developing painting application in which i need to save my painting.
To save i need to show save file dialog , As i am implementing MVVM pattern i can't directly use event handler.
But while implementing i thought of using PropertyChanged event directoly.
I have implemented INotifyPropertyChanged in ViewModel , I have bind all commands.
In save command in ViewModel i have called
OnPropertyChanged("Show Save Dialog"); // in ViewModel
and in code behind of user control I have added event handler as
ViewModel.PropertyChanged += new // in code behind of user control
System.ComponentModel.PropertyChangedEventHandler(ViewModel_PropertyChanged);
and in ViewModel_PropertyChanged i have
switch (e.PropertyName ) // in code behind of user control
{
case "Show Save Dialog": ShowSaveFileDialog();// this function shows dialog.
break;
}
This works fine in my situation but I don't know the dark side of this implementation.
Is it right ????
Right? There is no right or wrong, only the best choice at the current time. The only way for purists would be to abstract away the process of gaining such input from the user behind an interface, then create a View class which serves this interface and inject it somehow (IoC/DI, or perhaps by composition in the xaml if your ViewModels are instantiated that way).
Personally, I wouldn't spend too much time worrying about this, unless you must worry about this. I've done it both ways. For your average MVVM app, I think it is no great crime to just use a MessageBox, OpenFileDialog, etc. For heavily tested apps, you'll need to abstract it away. And there are other situations that demand it as well. For example, I have code that exists in an application and in a Visual Studio extension. VS has its own dialog types which should be used instead of, say, MessageBox. So abstraction is appropriate. But I wouldn't invest the work unless I had a reason to.
Why don't you just create a custom event? Something like this in your ViewModel:
public event EventHandler<EventArgs> ShowSaveDialog;
and then use
ViewModel.ShowSaveDialog += OnShowSaveDialog;
private void OnShowSaveDialog(object sender, EventArgs e){
//handle the event
}
I wouldn't just "abuse" PropertyChanged like that. There's probably nothing wrong with your implementation, it just doesn't feel right. Also, you're using magic strings, but if you have a custom event it's much more declarative, and other users of your code will immediately figure out there is a way to subscribe to this event.
If you need to pass extra information, then make a implementation of EventArgs and add the properties you need.
Well as Will said there is no right or wrong ... only best choices!
Personally, I tend more to the purist side and try to architect a system to have a clear separation of concerns ... but that's just me!
Here is an answer I gave to a post dealing with the same problem as yours. There I show the two current approaches floating around when you want to keep your view model clean of any view code.
But again, choose the way that best fits your needs/preferences!

MVVM + Implementation of View specific functionalities called by the ViewModel

here is my "problem" I want to resolve:
I have got many "View only" specific functionalities for example:
Change the ResourcesDictionary of a View at runtime (for changing skins from black to blue or whatever)
Save and restore View specific settings like the view size, or grid properties set by a user
...
All those functionalities have nothing to do with the ViewModel, since they are really view specific and might only fit to one client (View) of a ViewModel (in the case a ViewModel has got more than one client). The examples above are only two of a large amount of functionalities I want to implement, so I need a more generic solution instead of solutions that only fit those two examples.
When thinking of a solution I came two the following approaches
Create a ViewBase that inherits from DependancyObject. I dont like this solution because it somehow breaks the idea of the MVVM pattern where a View has no code behind. And to call this methods I somehow need to reference the View in my ViewModel which also negates the idea of seperation of concerns.
Create an IView interface. As dirty as the first approach. Each View needs to implement IView and therfor has code behind. Also the ViewModel needs to "somehow" know the IView implementation to call its methods
Bind Properties of the ViewModel to Triggers, Behaviours, Commands of the View. This approach seems to be the best, but I think I will run in a limitation of usage very fast because some functionalities might not work with this approach. For example just Binding a resourceDictionary to a View might not work because a merge is needed for correct display of new resources. Then again...I have view only specific functionalities / informations (like a resourcesdictionary) in the ViewModel, but only a specific client of the ViewModel uses this property.
If anyone of you already had the same problem and got a smart/smooth (and mostly generic ;) ) solution for my problem, this would be great.
Thank you
The easiest way to do that without introducing coupling between the View and ViewModel is to use a Messenger (also called Mediator in some frameworks). The ViewModel simply broadcasts a "change theme" message, and the View subscribes to that message. Using the Messenger class from MVVM Light, you could do something along those lines:
Message definition
public class ThemeChangeMessage
{
private readonly string _themeName;
public ThemeChangeMessage(string themeName)
{
_themeName = themeName;
}
public string ThemeName { get { return _themeName; } }
}
ViewModel
Messenger.Default.Send(new ThemeChangeMessage("TheNewTheme");
View code-behind
public MyView()
{
InitializeComponent();
Messenger.Defaut.Register<ThemeChangeMessage>(ChangeTheme);
}
private void ChangeTheme(ThemeChangeMessage msg)
{
ApplyNewTheme(msg.ThemeName);
}
I've long since adopted the way of thinking that Patterns were made for Man, not Man for patterns. Quite often you'll see a situation where MVVM doesn't fit and to resolve it, very smart people have come up with ways to get around it, while maintaining the pure MVVM look.
However, if you subscribe to my school of thought, or if you just like to keep it simple, another way is to allow the ViewModel to reference the view; via an interface of course, or that would just be terrible programming practice. Now the question becomes, how to get the view into the viewmodel?
the simplest way would be to do this in the view's dataContextChanged event. However if you want to try something different, how about using an attached property or dependency property to inject the view into the viewmodel?
I've successfully used this techniques on a number of WPF projects and don't feel dirty or somehow compromised. I call it MiVVM or Model Interface-to-View ViewModel.
The pattern is simple. Your Usercontrol should have an interface, call it IMyView. Then in the ViewModel you have a property with a setter of type IMyView, say
public IMyView InjectedView { set { _injectedView = value; } }
Then in the view you create a dependency property called This
public MyUserControl : IMyView
{
public static readonly DependencyProperty ThisProperty =
DependencyProperty.Register("This", typeof(IMyView), typeof(MyUserControl));
public MyUserControl()
{
SetValue(ThisProperty, this);
}
public IMyView This { get { return GetValue(ThisProperty); } set { /* do nothing */ } }
}
finally in Xaml you can inject the view directly into the ViewModel using binding
<MyUserControl This="{Binding InjectedView, Mode=OneWayToSource}"/>
Try it out! I've used this pattern many times and you get an interface to the view injected once on startup. This means you maintain separation (Viewmodel can be tested as IView can be mocked), yet you get around the lack of binding support in many third party controls. Plus, its fast. Did you know binding uses reflection?
There's a demo project showcasing this pattern on this blog link. I'd advocate trying out the Attached Property implementation of MiVVM if you are using a third party control that you cannot modify.
Finally may I suggest to find the best tool for the job is almost always the best programming approach. If you set out to right "clean" or "correct" code you are often going to hit a wall where you need to change your approach throughout.
When you said
I have got many "View only" specific functionalities for example:
that makes me think that you are mixing the "What" and the "How". I'll explain what I mean by this.
The what is your app requirements:
Change skin color of app
Save & Restore
Size
Grid properties
I argue that the above has everything to do with your ViewModel, your VM should contain simple or complex properties that can tell your View what it wants to do e.g.
public class SettingsViewModel
{
public Color Skin { get;set;}
public Size ViewSize {get;set;}
public GridProperties GridProperties {get;set;}
public void Save() {//TODO:Add code}
public void Restore() {//TODO:Add code}
}
your View would bind to that ViewModel and implement the "How".
If you're creating a web app then the how will take the ViewModel and create html. If you're using WPF you bind to those properties in XAML and create your UI(which might cause you to switch out ResourceDictionaries etc.)
Another thing that helped me out is to realize the asymmetrical relationship between the View and the ViewModel. In it's purest form the ViewModel should know nothing of the View, but the View should know everything it needs to know about the ViewModel.
That's the whole point behind separation of concerns.
Responses to your "solutions":
Your first option violates MVVM principles, have you read this article?
I believe this article will help you come to terms with view selection based on the ViewModel.
I don't know of what "limitations" you will come across, but WPF is quite robust and there will be solutions available.
I agree that View specific functionality should stay in the View (Save and Restore the window size, set focus to a specific control, etc.).
But I don’t agree that the introduction of an IView interface is ‘dirty’. That’s a common design pattern called Separated Interface which is described in Martin Fowler’s book Patterns of Enterprise Application Architecture. Furthermore, code-behind is not ‘evil’ as long the code relates to View specific functionalities. Unfortunately, that’s a common misunderstanding in the MVVM community.
If you give the introducing of an IView interface approach a change then you might find the WPF Application Framework (WAF) interesting. It solves our issues through this interface. You are going to see this in the sample applications.