How can I use the new GWT MVP framework? - gwt

I need a tutorial for the new GWT MVP framework which is presented here.
The description Google gives is a little bit short for me. What are the meanings of — and how do I use — the following?
Activities
Places
Eventbus
ClientFactory
PlaceHistoryMapper
ActivityMapper
Also, where are the models in this new framework?

Places
These are classes that encode information about where your program has navigated. You might make a Place that means, "I'm on the home screen," and another one that means "I'm editing the user with id 52384. I think a better name for these would be PlaceTags, because they are not actually a place themselves - they just indicate where your program is. The URL is hooked to Places in a PlaceHistoryMapper, in which you can say, "hey, #home should generate a HomeScreenPlace and #edituser:52384 should generate a EditUserPlace (maybe constructed with a field you set to 52384).
Activities
These start and stop your code. Each Activity has a start method that is called when appropriate. You determine what "when appropriate" means by making an ActivityMapper, which has a function called getActivity. getActivity accepts a Place, and you have to decide which Activity to return. If the Place is whatever you've coded to mean "I'm on the home screen," you might return a HomeScreenActivity, and if the Place means "I'm editing the client with id 523584," you might return a EditClientActivity. You can add methods or a constructor to an activity to pass in an id like 523584.
EventBus
This is an object the different parts of your program use to communicate. If you don't want to, you don't need to know very much about it - you can just plug it in where indicated in Google's documentation (that you linked to)
ClientFactory
This is a centralized object whose only responsibility is making other objects. You can also skip this concept if you want to simplify things - you'll just be missing out on the central organization of your objects. The advantage is that if you want to switch them out later for, say, a mobile version, or a mocked-up-for-testing version, you can do so all at once within a single place and the rest of your program doesn't have to change at all. You can also reuse the same objects easily when coordinating from a central place, so you don't have to re-create the whole main screen every time someone goes to #home.
Your Actual Program
All this stuff is just for navigation. Your models, views, and presenters are all set up in each Activitys start() method, which the framework calls when your app should navigate to a new place. In the start method you should start up your presenter (usually using a new instance) and start up your display (usually reusing an instance - the client factory is good for this). When you've created your display, you let the framework know by setting it as the widget for the AcceptsOneWidget that the framework passed into your start method.
This is incomplete, but a good supplement to the docs you mentioned: http://code.google.com/intl/de-DE/webtoolkit/doc/latest/DevGuideMvpActivitiesAndPlaces.html

I would also recommend you to carefully listen to the Google I/O presentations, they are a golden key to understand the GWT philosophy:
http://www.google.com/events/io/2010/
http://www.google.com/events/io/2009/
Specially these ones (try to keep a more holistic view of the MVP framework). They do not talk about the real GWT implementation but they give you basic knowledge of MVP. I still am an 8 months noob, so from noob to noob :)
Ray Ryan's overview of the MVP paradigm. Great resource (it was an enlightening for me).
http://www.google.com/events/io/2009/sessions/GoogleWebToolkitBestPractices.html
http://www.google.com/events/io/2010/sessions/architecting-production-gwt.html
Daniel Danilatos's testing for GWT. Here you will understand why all the fuzz for MVP!
http://www.google.com/events/io/2010/sessions/gwt-continuous-build-testing.html

Related

Data ownership and reference in MVVM (specifically C++/WinRT, UWP, WinUI)

I've set up a very simple (Universal Windows) App in C++/WinRT.
It's just App <- MainPage <- DataViewModel <- Data for now.
MainPage has some Sliders etc. which are bound (x:Bind) to DataViewModel, which contains an instance of Data. Working fine so far.
However, the Data is a member of DataViewModel. This seems to be an obvious code smell. Data should not be "owned" by the GUI. All Examples/Samples I've come across seem to be set up like this, though.
I also want to run a background thread (pure C++ code) that works with one and the same instance of Data.
The question: Who "owns" Data. How do I connect things? How to pass the reference?
My best idea so far: The App class itself should just own the one instance of Data. The MainPage ctor should take a Data& and pass it on to the ctor of DataViewModel. However, I don't seem to be able to write a custom ctor for MainPage, because there's generated code involved.
Just pointing me to well coded Sample App would also be appreciated.
IInspectable (in the comment above) makes a noteworthy point: "Ownership really only matters when non-static lifetimes are involved. If Data represents data with static lifetime then there's nothing inherently wrong with exposing it through a static App class member."
In this vein, don't limit your thinking of Data (i.e., the model) to just object(s) which some other object owns. The model should be thought of as a wholly independent component.
Let me approach this notion from another angle. Most people will readily describe MVVM as three independent "layers" or "components" or what have you, wherein the model "doesn't care" about the view model, which in turn "doesn't care" about the view.** In code (as you have seen yourself), you're probably going to find some clear cut ownership patterns to reflect that basic premise. For example, if we're following the the "view-first" approach like the Microsoft samples, you'll start with your App object, which owns an instance of a view object, which in turn instantiates a view model instance.
But the key to MVVM is not who owns whom, it's the relationships between those layers. If you wanted to, you could write a program where, say, the views and view models were all static members of the App class and still have a (conceptually) textbook MVVM structure once everything is hooked up. From that perspective, it doesn't matter where ownership resides.
Now, the thing about Microsoft samples like the Photo Editor is that ultimately they're just demonstrations of how things can work, not a treatise on design patterns. Consider when your data is coming from a database or a web service. Where do you draw the conceptual line between model and view model? The question may sound pedantic, but the way you evaluate these things influences your design decisions.
Which brings me back to your specific question. If it seems like code smell to you when examples you find online stick the model data any old place, you're not wrong. In "real life," the model can be an entire API, not just one illustrative class. You'll potentially have an elaborate subsystem delivering data to you that depends on services completely separate from your application. Or it might be an opaque third-party API that you're calling into via global functions, etc. Just remember that the key isn't "ownership," it's (the conceptual) "relationship." ***
** As a side note, you mention Data being a member of DataViewModel and describe this as Data being "'owned' by the GUI." Ideally, the view model should have no inherent ties to the UI, just application logic. Don't think of it as an extension of UI functionality.
*** But please don't take this post to imply that the actual implementation of the MVVM paradigm isn't important. That's true of any design pattern. The exact form that implementation takes depends on the specific application and whatever your boss wants you to do. All I'm saying is, don't get hung up on ownership. :)

How Build GWT Application using MVP

I have great experience in programming by using java and other languages.
I need anyone who has great experience in using GWT with MVP to explain how to build GWT Application using MVP:
View package : explain what should be in view class.
Client Package: explain what java files are supposed to be here and what is the benefit from each file.
Server Package: I think here all services files( RPC ).
Activity Package: Explain what is the benefit from the classes here , I think here we we connect events with controls in view classes( Am I correct?).
Place Package: I need to understand this very well.
Also what is the benefit from Clientfactory java file?
what is eventbus?
what is placecontroller?
please if you can order which file should be coded one after another?
Thank you in advance,
1) View is a widget with link to its presenter. It should notify presenter about ui events which should be processed.
2) Views, presenters, client(not shared with the server side) model, places, activities, PlaceHistoryMapper, ActivityMapper. About benefits see below.
Are you understand presenters well? According to your question i assume you confuse it with activities.
1.1 ) Presenter creates and manages view, makes rpc and most of 'logic' stuff.
3) You are right, server package is just a java server logic.
4) Activities link places and presenters. I will return to describing activities below.
5) Place has name, token and own Tokenizer which transforms its place to a token and other way round.
6) I didn't use ClientFactory. I prefer dependency injection with google-gin(gwt client version of guice)
7) Event bus is... I couldn't describe better than official javadoc does :)
Dispatches Events to interested parties. Eases decoupling by allowing objects to interact without having direct dependencies upon one another, and without requiring event sources to deal with maintaining handler lists. There will typically be one EventBus per application, broadcasting events that may be of general interest.
8) PlaceController knows where you are(in application :) and may change current place. (obviously, it has getWhere() and goTo(Place) methods)
9) Firstly you need to code application's singletones like PlaceHostoryMapper and ActivityMapper.
PlaceHostoryMapper provides history and converting tokens to places by segregating all PlaceTokenizers.
ACtivityMapper segregates all places and activities and provides second ones by first ones.
Views and presenters are based on interfaces. Next I would declare such interfaces.
Then write places. Then you able to code activities because you have places and interfaces of presenters.
Then in any order implement views and presenters, map activities to places in ActivityMapper and register PlaceTokenizers in PlaceHistoryMapper.
I assume now you have more questions, feel free to ask in comments or by contacts in my profile :)

GWT MVP introduction questions

I have read a lot of gwt-mvp questions that are asked here, but since i'm totally new to this design pattern I would like to ask some questions:
[1] The Activity-Place pattern is a different pattern than mvp?
[2] In the MVP pattern presenters contain the logic. Now the logic of the widgets/controls is defined in the Activities?
[3] The CustomPlace classes are fixed (as the Eclipse plugin constructs them) or can i put data/methods and what kind?
[4] What is the use of the Presenter interface inside a CustomView? What data/methods would make sense to add into it?
[5] I want to build an application that will use many data structures that will be saved into a database. I have read some other posts here and I will make the Model part of MVP live inside each Activity. So i think to create each time the data structures of each activity at start and load its values (if necessary from db) and will update the database after the user goes to another view. What do you think about this approach?
Let's start by debunking one myth: Activities/Places have nothing to do with MVP. Places is about navigation, Activities are about "componentizing" the UI wrt Places. On the other hand, MVP is a design pattern, it's about how to organize your code.
Many people are using their activities as their MVP-presenters, but it's not enforced. The GWT team is trying a new approach where the activity is distinct from the presenter (work underway in the mobilewebapp sample if you want to follow what's going on there). You could also have your activity being your view and making use of an "internal" presenter (similar to how Cell widgets work)
A Place is more or less a URL. You can put whatever you want in it. I'd suggest making places immutable though: build a Place, goTo it, make use of its properties to build your UI.
That's about MVP then. This is only needed to decouple your view and presenter, mostly to make mocking in unit tests easier (this is particularly of the view interface though, not much for the presenter one, unless writing a test harness for you views). In some cases, you might also want to use the same view with distinct presenters; they'll all implement the same interface so the view can talk back to them.
How about the closing of the window/tab? I'd rather use a periodic auto-save, or an explicit save button; and implement mayStop so it prompts the user when there are unsaved changes (similar to how most desktop office apps work —e.g. MS Word or LibreOffice—, and GMail if you try to navigate away before your mail draft is auto-saved)
The Activity-Place is an implementation of the pattern. Google introduced gwt-mvp pattern at Google IO, but only provided it's implementation as part of GWT about a year later.
Yes Activities contain business logic. No, widgets/controls usually do not contain any logic, they just fire events based on user action. The logic that acts upon those events is written by user and resides elsewhere.
I don't use Eclipse, so wouldn't know about Places generated by it. Normally custom Places can contain custom fields and methods. For example they can contain custom place token arguments, i.e. if place token is "#place:id1", than your custom Place could contain field holding this argument.
When View needs to call/access Activity, it does so via Presenter, which Activity implements. For example when user enters all data in a for and presses submit, then you could have a method in Presenter named submit(formData).
Preparing/loading data in activity.start(..) is a normal way of doing things. If particular activity is used a lot, then you might consider caching the data if appropriate.

Spring Roo + GWT: is RequestFactory still the way to go if "dual control" is required for every data operation?

One requirement in our application is to implement "dual control" for everything, including CRUD operations.
Just to be clear, "dual control" is a feature that requires a change in the data to be approved by someone other than the change requestor. So when a user make changes to data, it's not directly committed to production tables. I'm aware of several ways to implement this (e.g. staging tables) but thats for other time.
The question, with such requirement, do you think we should follow the standard "data centric" way of generated Roo + GWT (which uses RequestFactory) ?
Or we'll better off implementing our own "command pattern" based framework to support dual control?
I'm inclined toward the latter. My intuition (which based on 3 days play-around with Roo+GWT) says that RequestFactory is not designed with dual control in mind, and we'll hit a wall if we try to force our way in. Would be more than happy to be proven wrong here.
Have you looked at RequestFactory's ServiceLayerDecorator? It mediates all interaction between the payload processing and your domain objects and code. As an example, you could override the getProperty and setProperty methods to read from and write into some kind of "shadow" log that holds pending mutations.
If you need to implement ACLs for objects, methods, or properties, the loadDomainObject and resolveX methods can be used to control which server-side classes any given request can interact with.
To wire in a custom decorator, you can subclass RequestFactoryServlet and call the two-arg constructor. Alternatively, you can just instantiate a SimpleRequestProcessor using the object returned from ServiceLayer.create().
Implementation note: all of RequestFactory's default domain-interaction behavior is built using a series of ServiceLayerDecorators; check out the GWT source if you want to see example code for building a ServiceLayerDecorator. One thing to note is that if your decorator calls any methods defined in the ServiceLayer API, it should use the instance provided by getTop(). ServiceLayerDecorator instances are expected to be stateless and reusable, so if you need to maintain state across method calls, consider using ThreadLocal variables, similar to RequestFactoryServlet.getThreadLocalX().
It really depends what "user experience" you want, and particularly whether you want users to validate "diffs" of what has been changed, or approve the "new version" (snapshot).
If you want diffs, because RequestFactory only sends diffs (i.e. the actual changes the user, or you code, made to the objects) to the server, then intercepting setProperty calls as suggested by Bob is certainly one way to do it (to make Bob suggestion a bit clearer: you'd "store" the diff in a static ThreadLocal so you can retrieve it from your service call). You could also use "smarter" domain objects, that build an internal diff when their setters are called; the diff would then be accessible for each object on the object itself.
If you want snapshots, then you simply have to implement your services to store the modified objects in "staging tables" or whatever rather than in the "production tables"; and then "move" them to the "production tables" when the "approve" service is called.
One thing that's clear (to me), is that you have to model your services and/or objects around "dual control" and not try to do it within "simple CRUD" operations (i.e. the "save" is not a "save", it's a "send for approval"; and there's a separate "approve" operation).

Arguments against Inversion of Control containers

Seems like everyone is moving towards IoC containers. I've tried to "grok" it for a while, and as much as I don't want to be the one driver to go the wrong way on the highway, it still doesn't pass the test of common sense to me. Let me explain, and please correct/enlighten me if my arguments are flawed:
My understanding: IoC containers are supposed to make your life easier when combining different components. This is done through either a) constructor injection, b) setter injection and c) interface injection. These are then "wired up" programmatically or in a file that's read by the container. Components then get summoned by name and then cast manually whenever needed.
What I don't get:
EDIT: (Better phrasing)
Why use an opaque container that's not idiomatic to the language, when you can "wire up" the application in (imho) a much clearer way if the components were properly designed (using IoC patterns, loose-coupling)? How does this "managed code" gain non-trivial functionality? (I've heard some mentions to life-cycle management, but I don't necessarily understand how this is any better/faster than do-it-yourself.)
ORIGINAL:
Why go to all the lengths of storing the components in a container, "wiring them up" in ways that aren't idiomatic to the language, using things equivalent to "goto labels" when you call up components by name, and then losing many of the safety benefits of a statically-typed language by manual casting, when you'd get the equivalent functionality by not doing it, and instead using all the cool features of abstraction given by modern OO languages, e.g. programming to an interface? I mean, the parts that actually need to use the component at hand have to know they are using it in any case, and here you'd be doing the "wiring" using the most natural, idiomatic way - programming!
There are certainly people who think that DI Containers add no benefit, and the question is valid. If you look at it purely from an object composition angle, the benefit of a container may seem negligible. Any third party can connect loosely coupled components.
However, once you move beyond toy scenarios you should realize that the third party that connects collaborators must take on more that the simple responsibility of composition. There may also be decommissioning concerns to prevent resource leaks. As the composer is the only party that knows whether a given instance was shared or private, it must also take on the role of doing lifetime management.
When you start combining various instance scopes, using a combination of shared and private services, and perhaps even scoping some services to a particular context (such as a web request), things become complex. It's certainly possible to write all that code with poor man's DI, but it doesn't add any business value - it's pure infrastructure.
Such infrastructure code constitutes a Generic Subdomain, so it's very natural to create a reusable library to address such concerns. That's exactly what a DI Container is.
BTW, most containers I know don't use names to wire themselves - they use Auto-wiring, which combines the static information from Constructor Injection with the container's configuration of mappings from interfaces to concrete classes. In short, containers natively understand those patterns.
A DI Container is not required for DI - it's just damned helpful.
A more detailed treatment can be found in the article When to use a DI Container.
I'm sure there's a lot to be said on the subject, and hopefully I'll edit this answer to add more later (and hopefully more people will add more answers and insights), but just a couple quick points to your post...
Using an IoC container is a subset of inversion of control, not the whole thing. You can use inversion of control as a design construct without relying on an IoC container framework. At its simplest, inversion of control can be stated in this context as "supply, don't instantiate." As long as your objects aren't internally depending on implementations of other objects, and are instead requiring that instantiated implementations be supplied to them, then you're using inversion of control. Even if you're not using an IoC container framework.
To your point on programming to an interface... I'm not sure what your experience with IoC containers has been (my personal favorite is StructureMap), but you definitely program to an interface with IoC. The whole idea, at least in how I've used it, is that you separate your interfaces (your types) from your implementations (your injected classes). The code which relies on the interfaces is programmed only to those, and the implementations of those interfaces are injected when needed.
For example, you can have an IFooRepository which returns from a data store instances of type Foo. All of your code which needs those instances gets them from a supplied object of type IFooRepository. Elsewhere, you create an implementation of FooRepository and configure your IoC to supply that anywhere an IFooRepository is needed. This implementation can get them from a database, from an XML file, from an external service, etc. Doesn't matter where. That control has been inverted. Your code which uses objects of type Foo doesn't care where they come from.
The obvious benefit is that you can swap out that implementation any time you want. You can replace it with a test version, change versions based on environment, etc. But keep in mind that you also don't need to have such a 1-to-1 ratio of interfaces to implementations at any given time.
For example, I once used a code generating tool at a previous job which spit out tons and tons of DAL code into a single class. Breaking it apart would have been a pain, but what wasn't much of a pain was to configure it to spit it all out in specific method/property names. So I wrote a bunch of interfaces for my repositories and generated this one class which implemented all of them. For that generated class, it was ugly. But the rest of my application didn't care because it saw each interface as its own type. The IoC container just supplied that same class for each one.
We were able to get up and running quickly with this and nobody was waiting on the DAL development. While we continued to work in the domain code which used the interfaces, a junior dev was tasked with creating better implementations. Those implementations were later swapped in, all was well.
As I mentioned earlier, this can all be accomplished without an IoC container framework. It's the pattern itself that's important, really.
First of all what is IOC? It means that responsibility of creating the dependent object is taken away from the main object and delegated to third party framework. I always use spring as my IOC framework and it bring tons of benefit to the table.
Promotes coding to interface and decoupling - The key benefit is that IOC promotes and makes decoupling very easy. You can always inject an interface in your main object and then use the interface methods to perform tasks. The main object does not need to know which dependent object is assigned to the interface. When you want to use a different class as dependency all you need is to swap the old class with a new one in the config file without a single line of code change. Now you can argue that this can be done in the code using various interface design patterns. But IOC framework makes its walk in a park. So even as a newbie you become expert in levering various interface design patterns like bridge, factory etc.
Clean code - As most of object creation and object life-cycle operations are delegated to IOC container you saved from the writing broiler point repetitive code. So you have a cleaner, smaller and more understandable code.
Unit testing - IOC makes unit testing easy. Since you are left with decoupled code you can easily test the decoupled code in isolation. Also you can easily inject dependencies in your test cases and see how different component interacts.
Property Configurators - Almost all the applications have some properties file where they store application specific static properties. Now to access those properties developers need to write wrappers which will read and parse the properties file and store the properties in format that application can access. Now all the IOC frameworks provide a way of injecting static properties/values in specific class. So this again becomes walk in the park.
These are some of the points I can think right away I am sure there are more.