GWT MVP Pattern

gwt development GWT MVP Pattern

There is a ton of hype about the Model, View and Presenter (or MVP for short) pattern on the GWT forums and tutorial sites.  Unfortunately, there is just as much confusion about the GWT MVP Pattern as there is discussion.  The trick to this pattern is realizing that there really is nothing new about it, the pattern is a twist on some older patterns that you may be very familiar with.

Advantages of the GWT MVP Pattern

Before we get into the actual how-to of MVP, it is good to know why you actually should be using this pattern.  Just blindly doing something because it is the “new thing”, “everyone is doing it”, or “cool > useful” is usually a bad idea.  Know why you want to use something before you use it.

Decoupling

The first advantage for MVP is to decouple the view and the logic.  We all know that it is a good idea to decouple responsibilities as much as possible and the view and control code is no exception.  The old adage “let a class do one thing only and do that thing well” is sage advice and the MVP pattern helps with that.  When done properly, you will have one class that is the view and one that is the logic that controls the view’s behavior.  Of course, the best way to do this is through the use of interfaces.  The view would typically communicate via a presenter interface and the presenter would control the view through a view interface.

Unit Testing

If you are coding through the interfaces from the Decoupling section, then you will find unit testing your presenters a breeze especially if you are using a dependency injection framework like Gin and Guice.  When you create the instance of the presenter for the unit test, you can inject a mock of the view quite easily and control its behavior from the setup of the test.  The best part of this is you don’t have to use GWTTestCase.  This keeps you from needing to spin up a GWT container for every test which can be extremely time consuming.  Unit tests for presenters are just as fast as normal tests because they ARE normal tests.  There is never an excuse not to run them!

Coding to Other Platforms

One very cool feature, if you use the “correct version” of MVP, is that you can reuse your presenter logic on many other platforms for free.  Remember, you are writing actual Java code and there is no reason that you couldn’t drop it into a Swing or Android application.  Just rewrite the the view in whatever platform you are supporting, wire it to your presenter and ** POOF Magic ** you have a working application.

What do I mean by the “correct version”?  First, you need to code to interfaces because the presenter can’t be hard wired to the GWT version of your view.  Secondly, the view interface can’t expose any GWT specific widgets or interfaces.  For example, if your view interface has a method called getFirstNameHasText() and it returns the GWT version of the HasText interface, it won’t work on any other platforms.

GWT MVP Pattern Code Example

There are two main camps when it comes to using the MVP pattern.  The main difference seems to be the responsibility of presenter.  One side exposes interfaces for the presenter to register itself for change events from the widgets and the other delegates that responsibility to the view which in turn tells the presenter if something happens.  Personally, I am in the second camp because it looks cleaner and if you are going to be supporting multiple platforms you don’t need to write a bunch of wrapper classes to register to in order to expose the widgets.  I will show both versions of the GWT MVP Pattern and you can choose which one you like the best.

For this example, lets assume we have a form that we want to collect the user’s name.  This is of course a fairly trivial example, but when you do larger, more complex systems, it is really just a matter of copy and paste for each control on your form.  It doesn’t get more complex as you add more to the screen.

GWT MVP Pattern implementation #1

The first implementation is to completely decouple the view and presenter with interfaces and make them talk to each other through the interfaces (the “version” that I prefer) and not through registration of listeners.  The view and presenter interfaces would be something along the lines of the following:

As you can see, this will allow each other to let the other one know that something has changed but not know anything about how the other is implemented.  You will also notice the setPresenter on the view interface.  This may or may not be there depending on how you are creating your classes.  If you are using a dependency injection framework, you probably won’t have these types of “handshake” methods which leads to cleaner looking code.

Now to the meatier pieces, the presenter and view.  First lets take a look at the implementation of the presenter:

There are three main pieces to note in this code.  Line 10 is simply showing a bit of manual wiring that happens without dependency injection.  That way the view will have a reference to the presenter for later on.  Line 13 is an example of how the presenter takes data from the model and tells the view to display the information.  Remember, one of the presenter’s jobs is to be a bridge between the view and model.

Then on line 19 we have a situation that may not seem quite intuitive yet because we haven’t looked at the view implementation yet.  This is the method that will be called from the view when the name text box has changed values.  When the presenter is told about a change to the name value, it needs to save it into the model.

In the view, things get a little tricky if you aren’t used to any type of GUI programming.  I am also taking the liberty of assuming that the nameTextBox was somehow magically created and added to the UI.  There are several ways to do this such as programmatically doing it in the view constructor or using UIBinder.  How ever you choose to do it, don’t get hung up on this, it doesn’t matter to the pattern we are looking at.

The first item to notice in the view is on line 8 and 11.  Line 8 is simply registering for a change notification and line 11 is telling the presenter that it needs to do something with this new value.  The view really doesn’t care about what the presenter does as long as it does something.

Line 18 is getting called from the constructor of the presenter.  When the presenter tells the view what the actual value is, it needs to turn around and set the value into the actual control.

That is really all there is to the version 1 of the GWT MVP Pattern implementation.  It is pretty straight forward once you understand the few moving parts.

GWT MVP Pattern implementation #2

The second variation to the pattern is to have the presenter register itself to exposed interfaces and handle change events itself.  As in the last example, we will take a look at the interfaces before we get started with the real code.  Make note in this version that there doesn’t really need to be an interface for the Presenter because the view never is going to talk directly to it.

Line 3 is the big change here.  It is returning a HasText along with a new naming convention for the method name.  The HasText is a GWT interface that simply allows you to interact with the instance as something that contains and displays text in an unknown way.  If you are going to stick with this version of implementation, it is a good idea to adopt the naming convention as well.  It is quite easy to tell what you are going to be dealing with just by looking at the name.  If there was a method called getSaveHasClickHandlers(), you could safely assume that you are probably working with a save button that you need to register a ClickHandler with.

Line 4 is how you will register the presenter to listen for changes to the name widget.  Then when the value changes, the listener will in turn update the model.

Notice in the implementation that both of the methods return the nameTextBox.  It just so happens that TextBox implements both the HasText and the HasChangeHandlers interfaces.  Interestingly, with this version of the GWT MVP Pattern the view becomes a bit more simple.  It is only responsible for laying out the widgets and providing access to them

The presenter is where the largest changes come into play.  Just like the last example, it is responsible for initially setting the values into the widget.  It just happens that this is accomplished differently.  The presenter is also required to register handlers for change events so the model can get updated.

The presenter accomplishes its first responsibility on line 5.  It asks the view for the HasText and sets the value from the model into the view component.  This is fairly straight forward.  The second requirement of listening for changes has a bit more to it.  Line 8 and 11 is where the listening and updating is accomplished.  Line 8 asks the view for the HasChangehandlers and then registers a new ChangeHandler to take care of the changes.  When the value in the text box changes, line 11 will be called.  The presenter once again asks the view for the HasText, gets its value, and then sets it into the model.

Wrap Up Discussion

Both versions have merit and, to be honest, some of the decision comes down to personal style.  Some folks feel that one or the other looks more aesthetically pleasing to them.  In the end, the reason that I chose the first example over the second is because of unit testing.  There is far less that you need to actually mock out in the first version.  There are no HasText or HasChangeHandlers to mock, just the view interface (which is extremely easy if you are using Mockito or EasyMock).

No matter which version you use, the GWT MVP Pattern is definitely the right way to go.  Don’t get hung up on which version or all the nitty gritty details of all the arguments across the internet, just pick one and stick with it.  The important part is that you are doing it and using a great design!

Technorati Tags: , , , , , , , ,

GWT MVP, Activities and Places Confusion

GWT MVP, Activities and Places Confusion

gwt development

As people start to dig into the real meat of GWT, they usually find themselves scratching their head about how to design their application.  All of the tutorials about GWT give good introduction applications to give a general idea of the concepts, but that is where they usually leave off.  Most people begin their confusion with the differences between the MVP pattern and GWT’s framework called Activities and Places.

The confusion seems to grow and grow until the person finds themselves utterly frustrated and posting on forums, or even worse, giving up completely.  Don’t let this happen to you!  The trick to demystifying these two concepts is understanding that they have ABSOLUTELY NOTHING to do with each other.  You may see them mentioned in the same article online or in the same tutorial, but that just muddies the water.

Think of them as two separate design patterns.  (Yeah, ok, Activities and Places is more of a framework, but just go with it.)  Just like the Gang of Four patterns can be used together, MVP and Activities and Places can be used side by side.

So what are they?  Glad you asked!

Model, View and Presenter

The model, view, presenter pattern is really not much more than an extension to the old behavioral pattern called model, view and controller from a few years back.  The idea is that there is a class (presenter) that specializes in tying the data (model) with the presentation of the data (view).  The presenter is also responsible for logic and control of other items as well.  This concept is best thought of as separation of concerns for a well designed GUI application. 

Activities and Places

GWT’s framework called Activies and Places is used for managing “bookmarkable pages” in a GWT application.  As you are well aware of, a GWT application is one single page with a whole slew of dynamic processing going on.  Historically, it was difficult to be able to bookmark a specific spot in your application and come back to it, that is what Activities and Places for you.  As you navigate through your application, you wi
Another side benefit to using Activities and Places is history management.  Due to the fact that Activities and Places work directly off of the browser’s URL, the browser’s back and forward button is auto-magically now part of your GWT application.  When the browser back button is clicked, the URL is changed which in turn makes changes to the state of your activities inside your application.ll see the URL of your application constantly changing.  These individual “bookmarkable links” let you jump into your application and pick right back up where you left off before.  The great part is that you don’t have to worry about coding the link part yourself, that is the responsibility of the framework. 

Two peas in a pod

I think the biggest source of confusion is that these two patterns/frameworks work very well in conjunction with each other.  Its kind of like chocolate and peanut butter, put them together and you have yummy goodness but it is hard to tell them apart once they are mixed.

Just remember that MVP is used for separation of concerns and Activies and Places is used for URL and history management.

Here is a great talk about the major concepts of GWT (who doesn’t love David Chandler?)

Technorati Tags: , , , , ,

Google’s Developer Education Programs

I never cease to be amazed by Google and everything they keep doing for the general public, but wow, now the development comunity is really starting to feel the Google love too.  Google has launched a new education program called Google Developers Academy.  There is tons of tutorials and code walk throughs on this site to help you with just about any issue that you can imagine.  Some of the topics they cover are Android, Google Drive, and Google App Engine.  If you are confused about anything, this is the place for you.

Yet another great resource to get warm and fuzzies from is Google Developers Live.  Google has put together a place for you to get great information directly from Googlers and other developers.  Yes you read that right, people are actually online to help you out with your questions and issues.  When I saw this, I thought it was a fabulous way for Google to use their Google Hangouts.  What company have you ever seen that is willing to dedicate their staff’s time to help you out for free?

I’ve heard people people debating if they should use GWT or even just rely on Google technologies, I think the answer is clear.  They are heavily invested in your future and success.  You can’t go wrong with Google!

 

GWT is Going Open Source

GWT has been picking up steam over the last several years.  Every time Google releases an update, there is new and innovative changes including compiler speed, profiling tools, HTML 5 support, and WYSIWYG editors.  They have gone and done it again! 

Ray Cromwell, the technical lead, announced at Google I/O that once GWT 2.5 is released, the Google Web Toolkit is going to be released as an open source project.  Google is going to relinquish control to a committee which will decide the direction of this tool.Cromwell is going to be the committee chairperson along with folks from some well known companies such as Sencha, Red Hat, and Vaadin.  Other individuals include well known advocates such as Daniel Kurka, Christian Goudreau, and Thomas Broyer.

What is this going to do for the GWT community?  Great question.  Apparently, the group has already decided to change code repositories from Subversion to Git and to change the development effort slightly by creating two major code branches: a bleeding edge and more mature beta branch.  I for one am excited about being able to try out the latest and greatest they have to offer!

When is this going to happen?  From what Cromwell said, the major move is happening after GWT 2.5 comes out which is rumored to be around the first of August.

Are you concerned about this radical move from Google?  Many people are, but I would remind you back when IBM did the same thing with their Eclipse product.  It was a good tool before they opened it up, but once they did it became the leading tool in the market place.

What do you think about this move?  I’d love to hear your comments.

Global Exception Handling in GWT

gwt development

Ghosts in the Machine – When Exceptions Happen

There are times when your GWT application will simply do wild and crazy things and you have no idea why they are happening.  Or even worse, it will not do things that it is supposed to!  You can spend hours upon hours of pulling out your hair trying to trace down the exact area that is failing without any luck.  There is also the dreaded “It works in dev mode, but not when it is running in web mode!”  Just thinking about that makes me cringe.  Many times it comes down to knowing the tricks for exception handling in gwt. Continue reading

Hiring GWT Jobs – 4 Developers

gwt job 4 GWT Jobs Available

I wanted to put a word out to everyone that may be interested in working with GWT and other high end technologies such as the Casandra NoSQL database.

The job is focused on high end scalable systems targeted for the tech generation of the Navy and Marine Corp.  We use GWT for the front end technologies and Casandra and Oracle for the data store.  The team is a very tight knit group that is looking to add four additional people that are eager to learn and grow in their profession.  The group is fairly high paced, but certainly know how to have a good time.

They provide full benefits, medical, dental, and eye.  It is is for two years with the option to extend longer, possibly permanent.  The development group is located in Norfolk, VA.  If you’d like to get more information, please feel free to send me a personal email, jeffrichley@gmail.com or even call me, 757-576-9634.

GWT Upload in 3 Easy Steps

3 steps for uploading files in GWT

gwt development There are several very fancy and easy to use GWT Upload libraries that you can use in your applications but sometimes you just need a very simple interface to add an upload functionality to your application.  While the GWT client side of the upload process is the easiest part, many people miss the little tweak that you need to use.

If you want to use one of the fancier upload libraries for cool effects like upload status, I would recommend using GWT-Upload, GwtUpload, or Upload4Gwt.

In order to add this to your page, follow these three easy steps…
Continue reading

GWT GIN and Dependency Injection

gwt gin

The best book on the market for learning Google Guice

 

History and Theory of GIN

Several years ago, the Google Brainiacs delivered a dependency injection framework called Guice. The idea behind Guice is to let the framework create all of your dependencies and you simply tell it what types of objects you would like to have to do your job. The Guice system will determine the correct implementation classes for your requested interfaces and give them to you when appropriate.

This works extremely well in production mode, but it actually gives other benefits. This way of development helps you to design your software in a much more decoupled and modular way. You begin to lean on interfaces instead of concrete classes which is usually a very good thing. Because you are dependent on interfaces, your code becomes much easier to test.

Now fast forward a bit and you find yourself in a development group writing large systems with the Google Web Toolkit. You have read all about how Guice makes life easier and you are struggling to write unit tests for your GWT based code. You think to yourself, “Geez, wouldn’t it be nice if I could just use Guice?” Now you can do just that, GWT GIN (GWT INjection) brings automated dependency injection into the client side of development. It is based on Guice and uses the same annotations for its dependency injection. Continue reading

Technorati Tags: , , , , , , , , , , , , , , , , ,

Using GWT Autobeans in JUnit Tests

gwt autobeans

Using GWT AutoBeans in JUnit Test Cases

GWT AutoBeans

Where GWT AutoBeans Started

GWT has created an awesome framework called AutoBeans. It was originally created to be part of the backing to the GWT RequestFactory change management. The basics is that given an interface that extends ValueProxy which represents a bean (using the typical getters and setters), AutoBeans does the actual creation and managing of that bean.

The details aren’t really that important, just push the I believe button if you are using GWT’s Request Factory. AutoBeans is used to bridge the gap between the server side Entity beans and the GWT front end’s Data Transfer Objects. The problem that is introduced when using AutoBeans is using the interfaces in your JUnit Tests.

The Google Wizards actually made AutoBeans so that it can be used in GWT Applications as well as out of them, such as desktop and server apps. Due to this feature, you can also use them in your JUnit tests. Here is an example on how to do just that. Continue reading

Technorati Tags: , , , , , , , , ,

GWT Timer Example

gwt development

GWT Timer Example

From time to time, you will run into situations that you need to kick off some code sometime in the future or on a recurring basis.  The folks that have been writing JavaScript code have been doing this for years, but what is the CORRECT way to do this in GWT?

You can always dip down into JSNI (native JavaScript code) and create a timer service for yourself, but why do that when the magical fairies in the Google Wonderland have brought us the com.google.gwt.user.client.Timer class?  It is a very simple to use class that kind of has the feel of a classic Thread in Java.  The basic flow of developing with the Timer class is to create a timer, make a run() method, and then schedule it for some time in the future.  Here is an example of a GWT Timer:

The schedule method will make sure that your code is called at some time in the future that is at least as many milliseconds as you have specified.  That is an important thing to realize.  Just because you have told the code to run in 10 seconds doesn’t mean that it will be exactly 10 seconds from now.  This has a lot to do with the fact that the JavaScript engine isn’t running a bunch of threads at the same time.  It may need to complete what it is doing when the code is to be triggered.

Another option you have is to make your scheduler be recurring.  If you use the schedule() method it will run only once and if you use scheduleRepeating() it will happen on an ongoing basis.  As you can see the process on how to use a GWT Timer is pretty straight forward, nothing all that complicated.

Other Resources for GWT Timer

Technorati Tags: , , , ,