5 GWT Anti-patterns

5 GWT Anti-patterns

by Zack Grossbart on July 11, 2009

As GWT evolves into a senior technology we are developing some good patterns for writing applications and finding some anti-patterns too. This article presents five GWT anti-patterns that are short-term gains and long-term losses. They are found in many applications, and even some of the GWT documentation, but they can get you into trouble. Avoiding these patterns keeps your applications fast, maintainable, and high quality.

1. Too Many AJAX Calls

The problem
GWT makes AJAX calls amazingly easy, but it can’t make them any faster. Every time you make an AJAX call back to the server it creates a new HTTP connection. HTTP is based on the idea of making a small number of requests for a relatively large amount of data. To support this, HTTP uses a connection scheme called a three way handshake. This handshake makes sure that you can send data back and forth without losing any of it. It is also expensive.

Every time you make an AJAX call you’re creating work for the browser, the server, and the network. The browser slows down dedicating system resources to establish a new server connection. The server spends time allocating a new thread to respond to the request, parsing all of the headers, and creating a set of new objects. The network slows down because it must handle all the traffic required to set up and tear down the connection.

The solution
Combine your AJAX requests into one call that sends back more data. This is the same idea that makes CSS sprites work so well. For each GWT page I like to create two AJAX calls getData and sendData.

getData is called once when the page first loads. It gets whatever data the page needs from the server. If your page isn’t showing dynamic data you can skip this call. sendData is called whenever the user changes data and tries to save it. Sure there are some complex interactions that need more, but two requests is enough for most pages. Combining requests makes your pages run faster and your servers handle more concurrent users.

2. Inline JavaScript

The problem
The promise of GWT is that you don’t have to write JavaScript and it delivers on that promise very well. Sure you have to write the occasional native method, but mostly you can focus on your Java code. Native methods can be difficult to maintain, but inline JavaScript is impossible.

The most common way to insert inline JavaScript is generating attributes like onclick, onmouseover, or onmouseout with one of the DOM helpers or as a string. You might do something simple in response to these events like change a CSS class for a hover effect or call a helper method, but it will get you into trouble. This type of code is difficult to maintain, can lead to cross browser incompatibilities, and prevents the GWT compiler from checking and optimizing your code.

The solution
The solution is simple, use the GWT listeners and handlers to handle these events. GWT provides a complete set of listeners to let you respond to mouse clicks, hovers, and drags with a clean coding model. Almost every instance of inline JavaScript can be replaced with a listener. If you absolutely have to use inline JavaScript, then make it a native method so the compiler can check and optimize it for you.

3. Listeners Instead of CSS Pseudo Classes

The problem
One way to make your code easier to maintain is pushing as much as possible into CSS. Style sheets are easier to change, don’t require a recompile, and are more likely to work in every browser the same way. It also gives you a single place to change the look and feel of your application that guarantees UI consistency. However, GWT developers often ignore CSS pseudo classes.

A pseudo class in CSS is a way of identifying a specific state in the DOM. The most common pseudo class is hover. It looks like this in a CSS file:

.myclass:hover {
    background: red;
}

The solution
This simple example will turn the background red whenever the mouse is over any element that uses myclass. You could create a mouse listener and hope you got all the events right, but the browsers do that work for you. Using pseudo classes means you write less GWT code, generate less JavaScript, and make faster running applications. It also make the code much more maintainable since you can get the effect by just adding a class declaration.

4. Window.alert

The problem
Window.alert, like e.printStackTrace, does not belong in deployed code. I know it is easy to write and useful for debugging, but the end result is ugly and unprofessional.

Window.alert can also cause bad behavior when someone clicks a link too fast. If your GWT page is in the middle of an AJAX call while a user click a link for a new page it will cause an exception. If you pop up an alert dialog it prevents the user from actually going to the next page.

The solution
The solution is to properly user-proof your application. Instead of showing an alert box create a place within your UI for error messages. Look at the way they handle errors in this example.

5. FlexTable

The problem
FlexTable is the workhorse of many GWT applications, but using table tags for layout is like mowing your lawn with a weed wacker. FlexTable feels like using layout managers in Swing. GridLayout works well in Swing, but a web browser is not a windowing toolkit and GWT is not Swing.

FlexTable uses table tags for layout under the covers and you should never use HTML tables for layout. The two biggest reasons for avoiding table tags are lack of flexibility and maintainability. Tables aren’t flexible. That means you can’t position then right or make them look really good. Tables aren’t maintainable because you can’t easily move things around or mix them with other elements. Try moving a table cell outside of a table and you’ll see what I mean.

The solution
The salvation from FlexTable lies in CSS layouts. CSS doesn’t just do fonts and colors, it can be your layout manager. There are many good articles out there about CSS layout, but it comes down to one simple fact: CSS works better. It is easier to maintain, looks better, and works more reliably across browsers. Need more proof? Check out any of the big websites, they all use CSS positioning. If you want to use GWT well you must know CSS

Further reading

Conclusion

As technologies mature we develop patterns and anti-patterns. They help us learn from the experience of others and avoid solutions that look good but come with hidden costs. I hope the anti-patterns in this article are helpful, but it is far from a complete list. What are the anti-patterns you’ve found with GWT?

4 More GWT Anti-Patterns

If you liked this article check out 4 More GWT Anti-Patterns.

  • http://blog.gerardin.info Olivier Gérardin

    I would argue that “too many AJAX calls” is not specifically a GWT anti-pattern but a rich-client anti-pattern. I experienced this with Swing clients too: as long as the client and server are on the same network and with little data, you don’t really care about optimizing the number or size of server calls. When you begin to have users on slow networks or with big latency, it begins to show badly, and then you need to really think carefully about how you handle server calls.
    The most efficient solution is to design UITOs (UI Transfer Objects) that are specifically designed to carry the data required to populate a screen (and no more than that) in one shot. Same for the other way when you save data, except it’s less crucial because you usually need to save much less data than you load.

  • Zack Grossbart

    Thank you for your comment Olivier,

    Making too many calls between the client and server has been a problem since client-server programming began. GWT is bringing many of those problems to the web along with the power of client-server architectures. UITOs are an excellent idea for making UI faster and minimizing network traffic.

  • http://www.dobesland.com/ Dobes Vandermeer

    Your hover example is a bit flawed because some browsers (IE, I think) don’t support :hover on any tag, only on an anchor tag. However, using a handler/listener for hover works for any elements, including table rows, divs, etc. etc.. So, be careful when using pseudo-selectors because they may cause some cross-browser woes.

    Most other pseudo-selectors suffer the same lack of cross-browser consistency.

    Also, it’s easy for people to feel like tables are “the devil” or somesuch but in fact they are very useful for one thing: displaying something organized into rows and columns.

    I do agree that using FlexTable to structure your UI could get you into trouble, because tables handle resizing a bit erratically across browsers. Unfortunately, tables are implicitly recommended by the GWT team simply by the fact that FlexTable, VerticalPanel, HorizontalPanel, and DeckPanel all use tables… in fact, tables are the only layout metaphor included in GWT out of the box unless you use FlowPanel.

  • Elias Mårtenson

    I keep hearing that tables are bad for layout and I keep trying to find a good justification why that is the case. The link that is provided in this article mentions the following points:

    * mixes presentational data in with your content.
    o This makes the file sizes of your pages unnecessarily large, as users must download this presentational data for each page they visit.
    o Bandwidth ain’t free.
    * This makes redesigns of existing sites and content extremely labor intensive (and expensive).
    * It also makes it extremely hard (and expensive) to maintain visual consistency throughout a site.
    * Table-based pages are also much less accessible to users with disabilities and viewers using cell phones and PDAs to access the Web.

    Out of these points, only the last one is in any way valid when it comes to GWT applications. All the others are handled by the abstractions provided by GWT.

    Say what you will about CSS, but it’s still much more limited than tables in what kind of designs can be created. Especially if you still have to support older versions of IE.

    I would love to see a good justification why using tables for layout in GWT is bad. Once I do, I promise to redesign all my GWT applications to accomodate for this. Until then, I’ll keep using HorizontalPanel and friends to create great-looking user interfaces.

  • Mirco

    “Style sheets are easier to change, don’t require a recompile, and are more likely to work in every browser the same way.”

    In the world where I live Style Sheets don’t work in every browser the same way (e.g. IE6!!!). For consistent layout its much easier to use a HorizontalPanel instead of CSS.

  • Mirco

    “Need more proof? Check out any of the big websites, they all use CSS positioning.”

    Lets look at the most popular page on earth: http://www.google.de/
    They are using an table for the layout of main part of the page. If you look at other google pages you will find a lot of table layouts because they care for their users instead of being slaved to rules like “tables are evil, css is good”.

  • Zack Grossbart

    Thank you all for your comments.

    Psuedo Selectors
    The hover pseudo selector is well supported for objects in IE 7 and 8. I’m using it on my other site Get The Eye. Psuedo selectors can get you into trouble in IE 6 because of the mysterious hasLayout property, so it is a little more complicated than just supporting anchor tags.

    Table Tags
    I’ve had the table tag debate many times. First off, table tags are good for displaying tables of data. They give the browser the chance to optimize the tabular layout and provide support for columns that is difficult to acheive with CSS.

    When you start using tables for layout you get pages that look like they were made 15 years ago. The controls sort of end up where you want them, but they don’t look very good. Table tags have got me into trouble with spacing issues, padding issues, and cross browser issues. A common problem I’ve seen with table tags are the labels on one side of the screen and the control on the other.

    Table tags are also difficult to maintain. Stylesheets can make your spacing and layout consistent across your entire application and you never have to worry that you set the padding to 5 on one page and 10 on the other.

    @Mirco, you are right that Google uses a table tag on their main page, they stay away from them for layout on most of their other applications. A good example of layout without tables is the sign up form for LinkedIn.

    Almost every designer I know stays away from table tags because they make designing good looking sites much more difficult. FlexTable works well for quick demos and proof of concept work, but they make professional level web design nearly impossible.

  • Elias Mårtenson

    @Zack,

    Thanks for proving my point. The LinkedIn sign-in page, like far too many current web sites completely fail at handling horizontal resize. The reason for this is that proper layout that accommodates for resize is very tricky to do without tables. The workaround most designers take if they don’t want to use tables is to simply lock the horizontal size at a certain width.

    Like I said in my previous post, I’d love to see a concrete reason why I should stop using table-based layout in my GWT applications, and I have yet to see one.

  • Zack Grossbart

    Elias,

    My biggest reason for using CSS instead of tables is that it is easier. CSS does take a little more effort to learn, but once you do each page is easier to create and make it look good. CSS is also much easier with dynamic layouts. Take a look at my Dynamic Grid Layout In JavaScript article. Writing the code to generate a few CSS properties is much more manageable than handling all of the TABLE, TR, and TD tags.

    …but that is just my opinion.

  • Elias Mårtenson

    @Zack,

    In general terms, what you say is correct. However, the above article as well as my comments were referring to layout within the confines of GWT.

    With GWT, making a self-contained widget using the table-based layout primitives is a lot more easy and manageable than using CSS. With CSS, you can’t simply move a widget to a completely different position in the DOM-hieararchy without having to rewrite a lot of the CSS. Especially if you want to have a proper design that adopts itself to the width (and height) of the browser window.

    Also, of course, there is no need to mess with table, tr and td tags when using GWT.

    So, to summarise: I agree with you on the advantages of CSS when designing a page using hand-written HTML. I absolutely do not agree when it comes to GWT layouts, which is what the article was about.

    At the end of the day I suppose it comes down to what one’s approach to GWT design is: Are you trying to build a web page using Java code, or are you trying to write a Java application that runs on a web page? I tend to gravitate towards the latter camp.

  • http://blog.project-sierra.de Stefan

    Nice article Zack.

    I suppose the suggested UITO is what Fowler called a Data Transfer Object (DTO).

  • Zack Grossbart

    Stefan,

    Thank you for commenting. I’ve heard them called many things, but encapsulating your data is always a good idea.

  • TheGWTcritic

    Why oh why did Google use anchor tags? If you want to web analytics or look at logs and see what is being clicked, outside of js tagging, this makes GWT hits impossible to track!? If you want to capture and montior all the requests just as they were clicked, you can’t because the HTTP protocol won’t pass the anchor tags, so you can’t see what is happening. If you wanted to recreate the entire session, just as it occurred, you can’t.
    I realize that they are doing everything client side, so it works for their code, but for analytics, debugging, monitoring, and session recreation it is a nightmare!

  • http://www.zackgrossbart.com Zack Grossbart

    This isn’t specific to GWT. As JavaScript applications get more complex there will be more processing on the client-side. Our little thin clients are getting thicker. If you want to track these operations on the server-side you can add JavaScript calls to tools like Mint or Google Analytics.

  • http://www.agiletech.nl mc

    Reading the debate about tables vs CSS I really feel that it completely ignores the fact that GWT is designed to enable developers to create web applications without the need to do the scripting, HTML. You can even leave the default CSS as it is. The point is that you can get a working application deployed very fast without thinking about tables.

    The DTO pattern just does not always work for me. The problem is a bit less obvious, it’s more an effort in finding the right balance. Consolidating all your ajax calls into two calls to get/set the data seems ok but you are also fixating the data structure that a particular page can use which reduces flexibility. How does this work when you’ve got widgets that you’d like to reuse everywhere?

  • http://www.zackgrossbart.com Zack Grossbart

    Thanks for your comment mc.

    GWT makes it easy to prototype, but there are other frameworks (JQuery MooTools) that are much better for prototyping. GWT excels at creating large maintainable applications.

    What you are really talking about is GWT inability to totally abstract you from HTML. You’re right. GWT doesn’t totally abstract you from GWT. Nothing does. I’ve never seen a programming language that totally abstracts you from the underlying architecture.

    The DTO pattern is one that you can follow more or less, but the basic idea is realizing that HTTP requests are expensive and combining them makes a lot of sense. We normally have many widgets and a helper class for saving the data.

  • Andrew Birkett

    Hey Zack, Interesting post… but I wanted to comment on item 5. FlexTable.

    Yeah, I totally agree tables died a long time ago when it comes to layout. However, when it comes to GWT there are various layout containers you can use that use div’s under the hood and that rely on good old css positioning.

    Gwt Flex table is great at what it’s designed for. Showing tabular data. I think its a case of use for what it’s intended for.

  • Aegean BM

    Favor CSS over table tags is one of those designer rules that is hard to explain.

    1. We’ve all listened to the experts tell us the orthodox way, only to see to see the wind shift another direction. So we’re skeptical. If it ain’t broke, don’t fix it.

    2. We favor the tool we know over the tool we don’t. I can get this page done in an hour using tables, or I can spend a day and maybe get it done with CSS.

    3. Tables have a scaling problem. A single table is usually simple enough. But then you put another inside it, and.. eventually you have tables in tables in tables. I’ve never seen tables go 4 deep because 3 deep is already insane.

    4. Tables, especially tables in tables, are a maintenance problem. Pay attention to how much time you spend on changes.

    5. Tables go away, except for true tabular data, for designers that go with CSS. It’s hard to explain to those who haven’t made the journey. They haven’t had enough table pain yet. They haven’t felt enough CSS relief yet. Until then, the CSSers appear as fanatics adhering to the standard du jour.

    6. Watch the trend. Every year, some tablers go on to CSS, no CSSers go back to tables.

  • Travis Biehn

    Your webservice could take a list of data points you need, and return a list of response objects you need. Single call, re-purposable, widget re-use.

  • Pingback: Which JavaScript Recipe Is Right For You? | Neweb

  • Pingback: Which JavaScript Recipe Is Right For You? | ShadesColour & Associates

  • Pingback: Which JavaScript Recipe Is Right For You? | Script Hunter

  • Pingback: Which JavaScript Recipe Is Right For You? - Goodfav Howto

  • Pingback: Which JavaScript Recipe Is Right For You? | Smashing Coding

  • Pingback: Which JavaScript Recipe Is Right For You? | CGBook

  • Pingback: Which JavaScript Recipe Is Right For You? | Smashing Magazine