GWT: MVP Presenter Interface - gwt

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.

Related

ViewModels talking to each other

I've just created my first c# / XAML application using mvvmlight and I've tried to implement the MVVM pattern as best I can (WP8 app). However, I've slowly morphed my code in to a certain style and I don't think its correctly implementing the pattern! Any advice on how things are supposed to be would help enormously.
For example, using mvvmlight I am making heavy use of the ViewModelLocator. Some of my viewmodels get created right away, like the SettingsViewModel (there is a SettingsView).
SimpleIoc.Default.Register<SettingsViewModel>(true);
And then elsewhere in my project, my other viewmodels will directly access this viewmodel for occasional information via a property or a method... like this;
mySetting = ViewModelLocator.SettingsStatic.GetSomeSetting(var);
My concern is that my viewmodels are talking to each other in this way more and more. The issue with this is that they probably can't be tested independently now because they require or assume the existence of other viewmodels.
Any pointers here would be great!
EDIT: Another example is having a PersonView, and the PersonViewModel has some helper methods for UI display. In some cases I have other views that need to display this info.... and I use the viewmodellocator to get to them, rather than writing the helper methods again in the current viewmodel.
You are right in thinking that viewmodels being dependent on viewmodels is going to cause trouble. When I need to have access to "global" settings in my app, I use an interface that can be injected in the constructor of the view model. So, You can create an ISettingsService that contains the properties and methods you need. You also create a design time setting service that mimics or fakes the data/properties of the ISettingsService Interface
then in your view model locator you use this:
if (ViewModelBase.IsInDesignModeStatic) {
SimpleIoc.Default.Register<ISettingsService, DesignSettingService>();
} else {
SimpleIoc.Default.Register<ISettingService, SettingService>();
}
Create the DesignSettingService and SettingService which both implement the ISettingsService.
As for you vewmodels, the SimpleIOC will resolve/inject the required elements passed into the constructor of the class. If you have a class/viewmodel called MyViewModel and it wanted to use the settingsservice then you would define the constructor like this:
private ISettingsService _SettingsAccess;
public New(ISettingsService SettingsService)
{
_SettingsAccess = SettingsService;
SettingProperty= _SettingsAccess.GetProperty;
}
This keeps the viewmodels decoupled as this service is resolved in the constructor, that way you can change the implementation of your ISettingsService without breaking every viewmodel that uses it.
I use a INavigationService to handle all the navigation events in my app, this allows me to cancel navigation based on another viewmodels properties without needing the other viewmodel to be directly called/referenced by the current one.
One view model should never directly call another view model. Using this method you can pass as many "services" as are needed to the viewmodel. Every viewmodel I use gets a dataservice that connects to my model in addition to the navigationservice. Ie. A viewmodel that deals with people gets an IPeopleDataService where this service contains all the CRUD operations that affect the database. That way I can change the people objects in the database and service functions without having to change the people viewmodel as well.
I hope this helps.

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
.

Real-world examples of populating a GWT CellTable using a clean MVP pattern?

We are using the GWT-Presenter framework and attempting to use CellTable to put together an updateable grid. It seems as though several of the GWT constructs for CellTable don't lend themselves to easily breaking up the logic into clean view and presenter code.
Examples: 1) Within the View's constructor, the CellTable is defined and each column is created by anonymous inner classes that extend the Column class to provide the onValue() method. 2) The FieldUpdater interface must be implemented to provide logic to execute when a user alters data in a cell. This seems like it would best fit in the Presenter's onBind() method, but FieldUpdaters often need access to the Cell or Column which belong in the view. CellTable does not have accessor methods to get hold of the Columns or Cells, so it seems the only way for the Presenter to get them is for me to create a multitude of member variables on the View and accessors on my Display interface.
Can anyone provide good examples for dealing with CellTable in GWT-Presenter or a comparable MVP
I think the main point of GWT MVP is that Presenters (Activities in 2.1) do not depend on View implementation, so that you can easily swap in mock Views for easy testing.
Further, it's OK to have Views that depend on Presenters (= call presenter methods), but not vice versa (well yes, but via interface).
Usually I just keep Presenter reference inside View, so that FieldUpdater anon inner classes can call methods in Presenter. You could put this methods in an interface, but it would make no sense since there is only one version of given type of Presenter.
Or, if you want to have things more decoupled, then just have View send a GWT Event which Presenter listens to.
Are you trying to avoid binding of Model class with View? i tried doing that for cellTable but it was becoming confusing to maintain code so i decided to let Model class couple with View. you can avoid this coupling by some generic arguments while creating view..
-Saket

How do GWT 2.1 data presentation widgets work in conjunction with MVP?

The Data Presentation Widgets in GWT 2.1 seem to have it all sewn up: model, view and presenter. So how does all of this data presentation goodness fit in with MVP? For example; how might I associate presenter (aka Activity) instances with the nodes of a CellTree? And is that even something that I should be trying to do?
EDIT (elaboration):
Where does the TreeViewModel belong? Is it rightly part of the View, or part of the Presenter? And how does one obtain a reference to the ListDataModel for a sub-branch of the tree?
It's OK to give your view a reference to your presenter, and vice versa. If your CellTree needs access to your presenter, define a function like setPresenter in the CellTree.
Another solution would be to create EventHandlers that attach to your view, and then have your presenter listen for those events and respond by calling into the interface of your view. Less coupled, more verbose. I like to create generic interfaces for both my Presenter and my View to keep them totally separate but still avoid having to deal with EventHandlers.

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

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