Showing posts with label DI. Show all posts
Showing posts with label DI. Show all posts

Sunday, November 13, 2011

Subjective thoughts on best practice with GWT applications.



If you have spent anytime with me you know I love GWT.  But in my humble opinion there are ways to build web applications that still involve the gamut of javascript frameworks and bog-standard HTML5 and javascript.  Through my vast and continued learning experience of GWT I am beginning to see it in its current guise as being great for building complex and large widgets embedded in a web environment that is built in a more traditional web application framework.  Using the word tradition is kind of absurd in the web application design sphere because a tradition is established in a matter of months and then disposed for a new tradition within a couple of years.  However we appear to be heading towards a path of convergence in how and the way we code.  I recognise this as entirely subjective but for companies adopting GWT for the first time, experimenting with complex GWT widgets, then embedding them into their existing web applications is a great way to start on the GWT path.

Model-View-Controller (MVC) and Model-View-Presenter (MVP) are becoming the de-facto design patterns for building desktop, web and mobile applications.  Developers pay attention, if these are not on your resume, get them on there as fast as possible.  You should not leave home without it.  Many frameworks in almost every language develop according to this pattern.  So whether you are using Ruby on Rails, Grails, GWT, Spring MVC, Backbone.js they all design their frameworks around this convention.  GWT is a little late to the game with regards to this and so two additional frameworks have been around for a while which in my opinion currently offer a lot more features than the "Activities and Places" inbuilt infrastructure.  These two frameworks are GWT-Platform and MVP4G.   They are both on Google Code and both have extensive user collaboration and input.  Developing outside of GWT in the standard HTML-CSS-JS arena backbone.js offers a Javascript implementation of MVC.  I haven't used it as of yet but from the brief tutorials I have read it appears to be very easy to use.

In a similar vein, Dependency Injection is also a must have.  Design your code to interfaces and inject interfaces at runtime.  This is achievable in GWT using Google GIN on the client and Google GUICE on the server.  However my current overwhelming suggestion on the server is the Spring framework.  If you are writing Java server code and not using Spring, you are probably writing lots of boilerplace bullshit.  Stop it now!.  My server side framework knowledge is limited so would love to hear from other developers on alternatives, but from what I have seen this is well adopted, supported and promoted in the media and job adverts.  Spring is about more than Dependency Injection but this is at the core of the framework.  If you want to develop modular, testable code then you need to use DI.

Using the Facebook web site as an example lets look at how you might construct this from scratch.  Some GWT developers will suggest that the whole site should be built in GWT.  I disagree but more on that later.  However I believe that you will have a more flexible and productive if you develop the complex parts of your web site in GWT and embed them into the website.   So when looking at your newsfeed the complex box that controls updating your status etc might be a small GWT application but it is embedded in an AJAX-controlled feed panel table.  The reason I think this?  Unless your whole team consists of ninja, ex-Google GWT developers that worked on the ad-sense or ad-words interface, then you are going to experience delays in your project as you migrate your developers to a new way or working.  By concentrating complexity in small manageable chunks you reduce your exposure to delays in your project.

Monday, January 24, 2011

Using Gin-Guice With Java Generics (Cell Table/DAO Example)

Last year was so interesting and I have discovered so many interesting methods, ideas, patterns, and frameworks for developing professional software.  A big proportion of this learning curve has been embracing Test-Driven Development and the necessary changes required to the structure of your code.  One design pattern is the Dependency-Injection (DI) pattern where an objects dependencies are injected into the constructor.  This allows us to clearly see what the dependencies of an object are, and using a framework allows us to inject our implemented classes.  Spring offers a DI framework, which I hope to experiment at some point, but for now, and because many of the Google GWT examples use it, I am using Google GIN on the client side GWT projects and Google GUICE on the server.

Explaining Generics is a little more complicated and I defer to someone more experienced.  So a quick web search yields this:
"Generics provides a way for you to communicate the type of a collection to the compiler, so that it can be checked. Once the compiler knows the element type of the collection, the compiler can check that you have used the collection consistently and can insert the correct casts on values being taken out of the collection."
Now here comes the tricky part.  How do we inject a generic type class using Gin/Guice?

I always like to lead by example so lets talk about the example used here.  Imagine you have a base class for all of your tables you are gong to render.  However depending on the annotation used where you inject the base table, then that dictates what the type of the generic class used.  In addition the annotation decides what ColumnFormatter class is used to render table.  So in summary:
  • 1 Base Class SohoTable<T>
  • Several ColumnFormatter classes depending on table used.
Declaration of SohoTable
public class SohoTable<T extends HasReadId> extends Composite implements
  HasEventBus, HasTableChangedEventHandler {
@Inject
public SohoTable(ColumnFormatter columnFormatter) {

Here the base class shows the generics declaration.  Here you can replace HasReadId with any interface your common DAOs implement.  For simplicity we just ensure that HasReadId has a method to get the unique Id of the row.

The constructor requires a ColumnFormatter implementation for the DAO object you are creating.   This is a little abstract, so hold off your questions until later.

ContactColumnFormatter
let us dig deeper into a real implementation.  So we have a table of Contacts which we are going to use the generic base class for therefore we need to create this class and implement the ColumnFormatter.
public class ContactColumnFormatter extends ColumnFormatter {

Create the annotation
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.FIELD, ElementType.PARAMETER })
@BindingAnnotation
public @interface ContactTableAnnot {

}

Ginjector
SohoTable getSohoTableOfContact();

Create the ContactTableProvider
public class ContactTableProvider implements Provider<SohoTable<Contact>>{

 private final Provider<ContactColumnFormatter> providerFormatter;

 @Inject
 public ContactTableProvider(Provider<ContactColumnFormatter> providerFormatter) {
  this.providerFormatter = providerFormatter;
 }

 @Override
 public SohoTable<Contact> get() {
  return new SohoTable<Contact>(providerFormatter.get());
 }

}
Here we inject the correct ColumnFormatter for the Contact table.

Wire up the classes in the ClientModule (AbstractGinModule)
bind(ContactColumnFormatter.class);
bind(ContactTableProvider.class);
bind(new TypeLiteral<SohoTable<? extends HasReadId>>(){}).annotatedWith(ContactTableAnnot.class).toProvider(ContactTableProvider.class);
This is where we where the main action takes place. All the subclasses are wired up. The final line is the cool one. We need to use a TypeLiteral in order to wire up the generic elements. The annotated item shows how to wire up the annotation with the correct provider.

This is all very good but how do I use it?
@UiField(provided = true)
SohoTable<Contact> contactTable;

@Inject
public RolodexView(@ContactTableAnnot SohoTable<? extends HasReadId> contactTable) {
  this.contactTable = (SohoTable<Contact>) contactTable;

Friday, June 25, 2010

Newbie confronts GWT, GUICE, GIN, MVP and Dependency Injection.

Well the life of a fairly new Java developer is interestingly complex.  I guess that is why I love computer programming its like solving little puzzles all day long.  Studying the concepts of OO using Java has been very interesting and has given my skill set a new edge.   Originally I come from an engineering background and have learned computer programming on-the-job.  This technique has gotten me through the last ten years of investment banks, universities and blue-chip companies but it hadn’t left me with a very good design metholody when it comes to applications.   I utilised OO rudimentarily, using classes as containers for similar functionality.  In the main still running a procedural based programming paradigm where most parts of the application have to know what the other parts are doing for it to work correctly.  Highly coupled you might say….

So where am I now?  Well through a process of SCJP training, examining example code, watching Google IO sessions, and attempting to program a small GWT application.  I am a lot clearer on some aspects, but on others, well this adventure has opened up a great many doors on how to design my programs.

Two design patterns which are paramount in my opinion for good design are Dependency Injection and a MVP architecture?  Why you may ask?  In short Google uses them and that’s good enough for me.
MVP stands for Model View Presenter and is similar to MVC except in our case the view knows nothing of the presenter, so you can swap out the views for different ones, i.e. a web page or an Android application, and your application still works.  As long as your view implements its relevant presenters interface. 

As a design pattern this approach appears to be very good and the example Contacts application that Google provides helps clear up any confusion from purely reading the articles.  What is interesting with the example is that the core of the application is demonstrated very clearly, allowing other developers to easily pick it up, and event bus and rpc handling is centralised, removing the ugly spaghetti code, that I currently, but have not yet talked about.  

At the moment I have developed a very simple CRM application using GWT located at: http://sohocrm.appspot.com.  Completing this project allows me to get my feet dirty and by doing so has lead me to these design methodologies which I now have to attempt to embrace and learn.  I can feel my brain whirring as I try to understand these concepts. 

So MVP is a good pattern because it gives a very clear architecture on how your application works.  However in order to clear up more of the spaghetti code we also need to utilise dependency injection.  Now I only have a basic concept of this, so please correct me if I am wrong in what I am about to say, but DI is this.   When instantiating an object you create additional objects which are utilised in order for the object to complete its class.  This might be any object which is declared with a new keyword.  What this means is that the current class is dependent on these other classes in order for it to work.   The dependency component.   Now in order to write modular code and to make testing easier, it would be good to have any dependencies injected into the constructor as an instance when the object is created.  That way you can clearly see what classes your objects are dependent on and it allows modular testing to be a lot clearer.  I think it applies to only classes which exist within your current project as I don’t think you will be injecting in int's, textboxes etc, but the exact delimination of this area is unsure at the moment – for myself – and I hope to clear that up over the coming weeks.    Google uses a product developed by itself called GUICE to do this on the server side java and another called GIN which is a GWT version for the client side.

How did I come across these technologies?  Well after building that relatively small application I noticed how spaghetti looking my code was and realised early on that this can’t be the way much larger programs such as Google Wave are constructed so realised, intuitively knew as we all do when we are accomplishing a task we aren’t quite proficient at, that there must  be another way.

So the next stage of my application is to re-write it in a MVP style.  Then take a look at how I can implement Gin and Guice to build a scalable, understandable and modular application.