GWT: Places, History and MVP by Example - java

Say I want to create a GWT app that consists of two simple "screens":
A Main Menu that users see when the app first starts up (they go to specific URL) - forget login screens, etc., for this simple example; and
An Edit Preferences "page"/screen/view that takes the place of the Main Menu when the user clicks a button on the Main Menu; this Edit Preferences screen also has a button that takes the user back to the Main Menu; thus
The user can simply go back and forth between the Main Menu and Edit Preference "pages" (this is GWT so its actually a single-page app) all day long
So the pseudo-code for this might look like:
public class MainMenuPresenter implements Presenter {
// mainMenuScreen may be a Composite that contains a Button for
// switching/navigating to the EditPreferencesView
private MainMenuView mainMenuScreen;
}
public class EditPreferencesPresenter implements Presenter {
// editPrefsScreen may be a Composite that contains a Button for
// switching/navigating back to the MainMenuView
private EditPreferencesView editPrefsScreen;
}
Questions:
How does a Place and its associated Activities fit into this paradigm? If it's a choice between MVP and Places/Activities, then how would this example look using the Activities/Places paradigm?
If MVP and Activities/Places can play nicely together (and are not mutually exclusive), then how could we implement GWT's History API here so that we can set MainMenuView as one "place" in history, EditPreferencesView as a second "place", and then allow the user to hit the Back/Forward browser buttons and keep toggling between them?
If MVP and Activities/Places are mutually exclusive, and I have to choose between the two, is there anything different about the code in Question #2 above that needs to change?
I'm also interested in how a Place ties into an ActivityManager, and how/who fires/handles PlaceChangeEvents, but I'll save that for later; I need to understand these concepts before I can move on to those. Thanks in advance!

I'll try to outline an example setup that could work in your situation. There are lots of variations, but I'd like to concentrate on a simple one (and encourage you to think up where this can be adjusted).
1. Define URL tokens
Choose some URL tokens like "#mainmenu" and "#editprefs" which will be appended to the host page's URL. They will be used for the browser history, so the back and forward buttons work etc.
The URL handling will be done automatically for you by DefaultHistorian. The PlaceChangeEvent will be fired by PlaceController.
2. Map tokens to Place objects
A Place object is simply the object oriented abstraction of a token - this is useful, because more advanced tokens can also take parameters which need to be parsed. You'll need a way to map the tokens to Place objects. This is the responsibility of PlaceHistoryMapper.
In my example, we'd simply implement PlaceHistoryMapper manually to map "#mainmenu" to a MainMenuPlace and "#editprefs" to an EditPreferencesPlace.
[Alternatively, it's also possible to use the #WithTokenizers annotation and implement an (empty) PlaceTokenizer for every type of place. You could then use the #Prefix annotation to specify "mainmenu" and "editprefs" as the tokens.]
3. Map the Places to Activities
A Place object itself doesn't do anything - as explained above, it's basically just an abstract token. The actual code will be run in an Activity. So you'll have to map Places to Activities. This is the responsibility of ActivityMapper.
In my example you'd implement it to map MainMenuPlace to a MainMenuActivity and EditPreferencePlace to an EditPreferenceActivity.
4. Activities and Presenters
For simplicity, in my example the Activities would also implement the Presenter. So MainMenuActivity would implement MainMenuPresenter. This is not necessary at all, but maybe a nice starting point. And this is where Places+Activities can connect with MVP. The two concepts don't require each other, but they work nicely together:
Activities+Places is basically about the connection between the history token and an Activity.
MVP is basically about the connection between a Presenter and a View.
If you let an Activity (or one of its delegates) implement a Presenter, you have connected both.
5. Quick overview
"#mainMenu"
---(PlaceHistoryMapper)---> MainMenuPlace
---(ActivityMapper)---> MainMenuActivity implements MainMenuPresenter

Related

Clean Architecture: How to reflect the data layer's changes in the UI

I'm trying to make a design based on the Uncle Bob's Clean Architecture in Android.
The problem:
I'd like to solve is how to make the changes generated in one repository to be reflected in other parts of the app, like other repositories or Views.
The example
I've designed a VERY simplified example for this example. Please notice that boundary interfaces has been removed to keep the diagrams small.
Imagine an app that shows a list of videos (with title, thumnail and like count), clicking a video you can see the detail (there you can like/dislike the video).
Additionally the app has an statistics system that counts the number of videos the user liked or disliked.
The main classes for this app could be:
For the Videos part/module:
For the Stats part/module:
The target
Now imagine you check your stats, then navigate the list of videos, open the detail of one, and click the like button.
After the like is sent to the server, there are several elements of the apps that should be aware of the change:
Of course the detail view, should be updated with the changes (this can be made through callbacks so no problem)
The list of videos should update the "likes" count for the given video
The StatsRepository may want to update/invalidate the caches after voting a new video
If the list of stats is visible (imagine a split screen) it should also show the updated stats (or at least receive the event for re-query the data)
The Question
What are the common patterns to solve this kind of communication?
Please make your answer as complete as you can, specifying where the events are generated, how they get propagated though the app, etc.
Note: Bounties will be given to complete answers
Publish / Subscribe
Typically, for n:m communication (n senders may send a message to m receivers, while all senders and receivers do not know each other) you'll use a publish/subscribe pattern.
There are lots of libraries implementing such a communication style, for Java there is for example an EventBus implementation in the Guava library.
For in-app communication these libraries are typically called EventBus or EventManager and send/receive events.
Domain Events
Suppose you now created an event VideoRatedEvent, which signals that a user has either liked or disliked a video.
These type of events are referred to as Domain Events. The event class is a simple POJO and might look like this:
class VideoRatedEvent {
/** The video that was rated */
public Video video;
/** The user that triggered this event */
public User user;
/** True if the user liked the video, false if the user disliked the video */
public boolean liked;
}
Dispatch events
Now each time your users like or dislike a video, you'll need to dispatch a VideoRatedEvent.
With Guava, you'll simply pass an instantiated event object to object to EventBus.post(myVideoRatedEvent).
Ideally the events are generated in your domain objects and are dispatched within the persisting transaction (see this blog post for details).
That means that as your domain model state is persisted, the events are dispatched.
Event Listeners
In your application, all components affected by an event can now listen to the domain events.
In your particular example, the VideoDetailView or StatsRepository might be event listeners for the VideoRatedEvent.
Of course, you will need to register those to the Guava EventBus with EventBus.register(Object).
This is my personal 5cents and maybe not closely enough related to your example of "The Clean Architecure".
I usually try to force a kind of MVC upon androids activities and fragments and use publish/subscribe for communication. As components I have model classes that handle business logic and the data state. They data changing methods are only to be called by the controller classes which usually is the activity class and also handles session state. I use fragments to manage different view parts of the application and views under those fragments (obviously). All fragments subscribe to one or more topics. I use my own simple DataDistributionService which handles different topics, takes messages from registered publishers and relays them to all subscribers. (partly influenced by the OMGs DDS but MUCH MUCH more primitive) A simple application would only have a single topic e.g. "Main".
Every part of view interaction (touches etc) is handled by its fragment first. The fragment can potentially change a few things without sending notifications. E.g. switching the subrange of rendered data elements if the rest of the app does not need to know/react. Otherwise the fragment publishes a ViewRequest(...) containing the necessary parameters to the DDS.
The DDS broadcasts that message and at some point reaches a controller. This can simply be the main activity or a specific controller instance. There should be only ONE controller so that the request is only handled once. The controller basically has a long list of request handling code. When a request arrives the controller calls to the business logic in the model. The controller also handles other view related things like arranging the view (tabs) or starting dialogs for user input (overwrite file?) and other things that the model is not supposed to know about but influences (Throw new NoOverWritePermissionException())
Once the model changes are done the controller decides if an update notification has to be send. (usually it does). That way the model classes do not need to listen or send messages and only take care of busines logic and consistent state. The update notification ist broadcasted and received by the fragments which then run "updateFromModel()".
Effects:
Commands are global. Any ViewRequest or other kind of request can be send from anywhere the DDS can be accessed. Fragments do not have to provide a listener class and no higher instance has to implement listeners for their instanced fragments. If a new fragment does not require new Requests it can be added without any change to controller classes.
Model classes do not need to know about the communication at all. It can be hard enough to keep consistent state and handle all the data management. No message handling or session state handling is necessary. However the model might not be proteced against malicous calls from the view. But that is a general problem and cannot really be prevented if the model has to give out references at some point. If your app is fine with a model that only passes copies/flat data its possible. But at some point the ArrayAdapter simply needs access to the bitmaps he is supposed to draw in the gridview. If you cannot afford copies, you always have the risk of "view makes a changing call to the model". Different battlefield...
Update calls might be too simple. If the update of a fragment is expensive (OpenGL fragment reloading textures...) you want to have more detailed update information. The controler COULD send a more detailed notification however it actually should not have to/be able to know what parts of the model exactly changed. Sending update notes from the model is ugly. Not only would the model have to implement messaging but it also gets very chaotic with mixed notifications. The controler can divide update notifications and others a bit by using topics. E.g. a specific topic for changes to your video resources. That way fragments can decide which topics they subscribe to. Other than that you want to have a model that can be queried for changed values. Timestamp etc. I have an app where the user draws shapes on canvas. They get rendered to bitmaps and are used as textures in an OpenGL view. I certainly don't want to reload textures everytime "updateFromModel()" is called in the GLViewFragment.
Dependency Rule:
Probably not respected all the time. If the controller handles a tab switch it can simply call "seletTab()" on a TabHost and therefore have a dependency to outer circles. You can turn it into a message but then it is still a logical dependency. If the controller part has to organize some elements of the view (show the image-editor-fragment-tab automatically after loading an image via the image-gallery-fragmen-tab) you cannot avoid dependencies completely. Maybe you can get it done by modelling viewstate and have your view parts organize themselves from viewstate.currentUseCase or smth like that. But if you need global control over the view of your app you will get problems with this dependency rule I'd say. What if you try to save some data and your model asks for overwrite permission? You need to create some kind of UI for that. Dependency again. You can send a message to the view and hope that a DialogFragment picks it up. If it exists in the extremely modular world described at your link.
Entities:
are the model classes in my approach. That is pretty close to the link you provided.
Use Cases:
I do not have those explicitly modelled for now. Atm I am working on editors for videogame assets. Drawing shapes in one fragment, applying shading values in another fragment, saving/loading in a galleryfragment, exporting to a texture atlas in another one ... stuff like that. I would add Use Cases as some kind of Request subset. Basically a Use Case as a set of rules which request in which order are allowed/required/expected/forbidden etc. I would build them like transactions so that a Use Case can keep progressing, can be finished, can be cancelled and maybe even rolled back. E.g. a Use Case would define the order of saving a fresh drawn image. Including posting a Dialog to ask for overwrite permission and roll back if permission is not give or time out is reached. But Use Cases are defined in many different ways. Some apps have a single Use Case for an hour of active user interaction, some apps have 50 Use Cases just to get money from an atm. ;)
Interface Adapters:
Here it gets a bit complicated. To me this seems to be extremely high level for android apps. It states "The Ring of Interface Adapters contains the whole MVC architecture of a GUI". I cannot really wrap my head around that. Maybe you are building far more complicated apps than I do.
Frameworks and Drivers:
Not sure what to think of this one. "The web is a detail, the database is a detail..." and the graphic contains "UI" in this Ring as well. Too much for my little head
Lets check the other "asserts"
Independent of Frameworks. The architecture does not depend on the existence of some library of feature laden software. This allows you to use such frameworks as tools, rather than having to cram your system into their limited constraints.
Hm yeah well, if you run your own architecture that is what you get.
Testable. The business rules can be tested without the UI, Database, Web Server, or any other external element.
As in my approach model classes neither know about controllers or views nor about the message passing. One can test state consistency with just those classes alone.
Independent of UI. The UI can change easily, without changing the rest of the system. A Web UI could be replaced with a console UI, for example, without changing the business rules.
Again a bit overkill for android is it not? Independence yes. In my approach you can add or remove fragments as long as they do not require explicit handling somewhere higher up. But replacing a Web UI with a console UI and have the system run like before is a wet dream of architecture freaks. Some UI elements are integral part of the provided service. Of course i can easily swap the canvas drawing fragment for a console drawing fragment, or the classic photo fragment for a 'take picture with console' fragment but that does not mean the application still works. Technically its fine in my approach. If you implement an ascii console video player you can render the videos there and no other part of the app will necessarily care. However it COULD be that the set of requests that the controller supports does not align well with the new console UI or that a Use Case is not designed for the order in which a video needs to be accessed via a console interface. The view is not always the unimportant presenting slave that many architecture gurus like to see it as.
Independent of Database. You can swap out Oracle or SQL Server, for Mongo, BigTable, CouchDB, or something else. Your business rules are not bound to the database.
Yeah, so? How is that directly related to your architecture? Use the right adapters and abstraction and you can have that in a hello world app.
Independent of any external agency. In fact your business rules simply don’t know anything at all about the outside world.
Same here. If you want modularized independent code then write it. Hard to say anything specific about that.

GWT - Separating role of presenter from activity

What advantages could be gained from divesting the role of presenter from an activity?
What are the roles/concerns that could be separated in order to dissect an activity from being a presenter?
Why would you want to separate them into two distinct concerns?
Under what circumstances would it make sense not to unify them?
Give examples, pros or cons.
I can see two main reasons to separate presenters from activities: reusability and testability.
Real use case for reusability: we have an illustration entity with properties like the photographer, copyright and date of shooting, which can be linked to documents. The legend of is on the relationship between the document and the illustration. You can edit both the illustration and the legend on their own screen, but we also wanted that the illustration could be edited from the legend screen. So we made a presenter for the illustration screen. The illustration activity is a really thin wrapper around that presenter, and the legend activity is a bit more complex, but reuses the presenter and view. The activities' responsibility is to provide the RequestContexts and do the fire() (the save/cancel buttons are on another activity, similar to the actions on Google Groups).
Hypothetical use cases for reusability:
for different form-factors, you want to aggregate things on the same screen or separate them on their own screen (e.g. master/detail), and when you aggregate them, having two activities might not be ideal. Using thin activities in the phone form-factor allows you to reuse the components (presenter/view) within a single activity in the tablet or desktop form factors.
reusing the same presenter on different platforms: you could possibly use the same presenter on an Android app and a web app (and even possibly an iOS app through java2objc), the view would be a native Android view or a GWT-based view, and the navigation would be handled by Android activities and/or fragments vs. GWT activities and places.
About testability (this is theoretical), you could then test your presenter without the hassle of the activity lifecycle (mocking the view), and then separately test the lifecycle (whether it correctly initializes and cleans up the presenter, fetches/caches the data, etc. mocking the presenter).
See also the commit message of https://code.google.com/p/google-web-toolkit/source/detail?r=10185
Ray's idea was to make MVP an implementation detail of widgets, just like cell widgets use internal presenters today. From the outside they're just widgets that you can compose tha way you want; on the inside they use MVP so you can test them without the need for a GWTTestCase.
First of all two Thanks for question which pushes me in to the longest research ever . :)
According to Thomos Broyer here.
Activity cannot talk with widgets,which presenter can do.
Two main areas of concern:
1- getting the data into the widgets:
how can this design be improved ?
Server (RequestFactory) ---> Activity ---> WidgetPresenter ---> Widget
here, RequestFactory hands in data to Activity, which then gives it to
the Presenter
which subsequently hands it to the widget.
2- getting the data from the widgets to the server
widget ---> WidgetPresenter ---> Activity ---> Server(RequestFactory)

GWT: Granularity of Places and ActivityMappers

I'm finally starting to "get" GWT. At any time, a PlaceChangeEvent can be fired on the app's EventBus like so:
History.newItem("token-for-some-new-place");
This adds the event to the bus, whereby a registered ActivityManager scoops it up and consults its internal ActivityMapper to give it the Activity associated with the PlaceChangeEvent's Place.
The Activity (similar to a presenter or controller object from MVP/MVC) then obtains any data that is needed (via RPC calls to the server) and executes any business logic and configures the final view (typically a Composite of some sort) to display.
As long as we're talking about a super-simple GWT app that only has one display region on its host page, then like I said, I "get" it.
Where I am choking now is what happens when you have an app that contains multiple display regions (areas that can be updated asynchronously from one another).
So I ask:
How granular are ActivityMappers supposed to be? Is there just one app-wide AppActivityMapper that maps all Places to all Activityies, or should there be some sort of ActivityMapper hierarchy/decomposition, where you have multiple mappers? (And if your answer to this is something along the lines of "this depends on the needs of your application" then please explain what requirements/needs drive the appropriate level of granularity!)
If a Place represents a URL token in your app (for the sake of making the Place a bookmarkable state), then what happens when you have a more complex app that has multiple display regions (D1, D2, D3). How does one URL token (i.e. http://myapp.com/#token-for-some-new-place) map to D1, D2 and D3? Wouldn't that mean ActivityMapper#getActivity would have to be capable of returning a list of activities (List<Activity>) whose start(AcceptsOneWidget, EventBus) methods would all get callled?
Thanks for any help here - code examples always rock.
A Place represents, well, a place. It answers the existential questions of where did I come from?, where am I? and where am I going to?.
For a given place, the screen that's displayed to the user can be complex, and divided into a bunch of display regions. Each one is governed by an ActivityManager, which asks an ActivityMapper which Activity to use for a given place, making everything loosely coupled (activities don't (have to) know where they're being used, for which place, which other activities are running concurrently, etc.)
So, you won't have a mapper that'd return a list of activities, but a list of mappers each returning one activity.
See:
http://blog.ltgt.net/gwt-21-places/
http://blog.ltgt.net/gwt-21-places-part-ii/
http://blog.ltgt.net/gwt-21-activities/
http://blog.ltgt.net/gwt-21-activities-nesting-yagni/

GWT Model View Presenter , Reusing Presenters ? Or Presenter - Presenter Communication

A rookie here.
I just started with Ray Ryan's Google IO talk and following some articles on Google Developers site. I have not used any of the GWT add-ons like GWTP or MVP4G or GIN or any other stuff. Just followed the contacts example on the GWT site and tried to model my case.
I have a DockLayout panel which has a header, a navigation tree on the left and a central main panel. All of this i have in a single DefaultView which implements DefaultPresenter .
Now i have a DialogBox which pops up when the user does something in the tree and this is modelled in DialogView and DialogPresenter respectively.
Now when i hide the DialogBox , i am ending up calling a new instance of DefaultPresenter from the AppController which by virtue creates a new DefaultView and all of my tree selections and other changes in the main central panel are gone.
Is it possible to re use instances of presenters without creating a new one on history change ? (for eg, DefaultPresenter in my case)
Is there a way in MVP pattern to pass controls between presenters with values persisting ?
How to load a existing instance of a presenter inside app controller on an event fire ?
Or have i got the whole MVP architecture thing wrong ? I am now planning to have different presenters and views for each of my components say HeaderPresenter / HeaderView, TreePresenter / TreeView , MainContentPresenter/MainContentView ?So that i will only create new instances of presenters which i need (like MainContentPresenter ) and keep the existing ones as it is (like TreePresenter and HeaderPresenter) Does this solve my problem ? How would i stitch all of this different views in the browser window ? I am not using UiBInder , just sticking to basics .
Help me out all you experts, i am in a deadlock !
When I read your question it felt like the answer should be an article, something along the lines of Stateful Presenter Architecture for GWT Apps. This is StackOverflow, however, which is all about conciseness, so let's see:
Answers
1. Is it possible to re use instances of presenters without creating a new one on history change?
Definitely. Nothing prevents you from switching between a bunch of singleton presenters injected with your views (the switching will happen in your implementation of ActivityMapper). Note the assumption from hereafter that your presenters are Activities.
2. Is there a way in MVP pattern to pass controls between presenters with values persisting ?
Since your presenters are now singletons they'll retain the state of their member variables. For message exchange between presenters, events and EventBus are your friends.
3. How to load a existing instance of a presenter inside app controller on an event fire ?
Your ActivityMapper instance, once registered with your ActivityManager, should suffice. The ActivityManager will rely on your implementation of public Activity getActivity(Place place) of the ActivityMapper interface to return one of your singleton presenters.
Resources
David Chandler's Google I/O 2011 GWT session touches on exactly this type of master/details architecture. I highly recommend it in general and for this question specifically the part following the 18th minute, when David begins a thorough overview of Activities and Places.

java / gwt UI coding - clean code

i've started on some basic java coding with gwt, and im getting a bit concerned about the heft of my main class.
For instance - how does one compartmentalize the keyhandlers, since they trigger a number of changes to the UI, how could i move this into a separate .class file and still be able to access all the various widgets in the main class, without having to pass everything to the handler (ie. all the widgets i manipulate after the click event).
i've googled but didnt come across any particularly good examples - know of any readily legible code-bases i could read to see how it should be done? (gwt's own tuts are pretty basic, and just kitchen-sink every thing into a single file)
thanks!
I hate to say something so unimaginative, but MVC works--it's not the ultimate, but it can start getting you organized.
EDIT: While searching on a semi-related topic, I came across this which has similar ideas to mine but goes into more detail.
What that means in terms of GWT is that you should think of just laying out your GUI components in one class, put all your event handling in a second and put your object model objects separate from the other two.
One way to accomplish this is to make most or all the controls on your GUI public members. This sounds kind of lame, but their usage is encapsulated inside the controller so it's not like you have uncontrollable access--in fact your access is clearer/better defined than if all your members were private but your view code was combined with the controller.
Specific tricks:
Have listeners be their own class. You can often reuse them-- in other words, avoid anonymous inner classes. I sometimes create a listener class and instantiate a new instance for each button/control that needs to have a similar effect when pressed. If I need it to act slightly differently for a given button, I'll pass something into the constructor of the "special" handlers so that they know to act a little differently. You can also create different handler sub-classes if necessary--I'm just saying don't forget that event handlers are classes, you can use inheritance and everything if need be.
One Very Old GUI Trick I learned a long time ago, try not to have various mini-handlers modifying the GUI in different ways, instead have all the "active" buttons and controls set a state within your GUI and then call a single method that applies that state to ALL the controls on your GUI. When you get beyond a trivial GUI this can be a life-saver. If I'm not being clear, leave a comment and I'll leave an example for you.
Property sheets:
There is a special case for GUIs--the property sheet style GUI. I've done a LOT of these and they are irritating as HELL. They tend to have dozens or hundreds of controls on them, each GUI control tends to be tied to a specific field in your model and there are just hundreds of lines of copy and paste boilerplate code connecting them, each group copied and pasted with a few items changed--at minimum it's like 3 lines of code per control (Create control, copy value in and copy value out).
I always write these with a "Smart" controller--one that can intelligently bind the control to some data without any unique code. This can get tricky and if this is your problem let me know in the comments and I can give you some general advice as to some tricks you might try. I've gone from a minimal reflective solution to a full-on XML based solution. Were I to do it again, I might consider annotation-based.
Example of MVC:
Note, this is just an example, there are a MILLION ways to do MVC.
In your MAIN:
Instantiate MyView
Instantiate MyModel
Instantiate MyController(myView, myModel)
myView.setVisible(true)
in MyView
probably extends Frame
Most components are public final (public final Button b=new Button())
If public members make you nervous, use getters--same EXACT effect as public final members with a little extra syntax.
Remember that you can set final members in your constructor.
May have general methods such as reset(), but MyController may be a better place for this.
in MyController
saves references to myView and myModel
adds listeners to myView where necessary (see advice on listeners above)
configures myView based on state of myModel
when "done" button pressed, copies state from myView to myModel
notifies myModel that it's data has been updated and destroys itself.
in MyModel:
This would be a typical model class, it would contain your business logic (mostly not used as part of the GUI, that's more like GUI logic in MyController. The controller would tend to set values in your business logic then call some method like updated() to cause some business logic to take control. It should know nothing of a GUI--this is your "pure" business class.
Sometimes the GUI might call an update() or some other method to trigger some data change and then reload the GUI controls from the Model--this is a fairly good way to integrate your business logic with your GUI without your model knowing about the GUI...
Also, as I said above, I would put more work into MyController if I was working with property sheets just due to the sheer number of lines of boilerplate that you end up with if you aren't smart about it.
Note that View and Controller are nearly always paired. You can't just replace a Swing view with a web view and expect the controller to remain unmolested--but the model should not ever change for the view or controller.
You should take a look at the best practices for GWT applications first:
http://code.google.com/events/io/2009/sessions/GoogleWebToolkitBestPractices.html
One of the concepts they talk about is that of MVP (not MVC) to structure your application. There's a sample project on Google Code that you can look at to understand how to structure a GWT application in this way:
http://code.google.com/p/gwt-mvp/

Categories

Resources