Pathfinder Blog
Topic Archive: Patterns

Defining RIA Interaction Patterns on time in Flex Agile Development

Putting more attention to User Interaction Design is naturally becoming a standard practice with RIA.

With RIA technologies, classic Interaction Patterns are only building blocks, not solutions. With raised possibilities, Patterns have become more complex.

Continue reading »

Dead Duck Typing and High Cohesion

I'm sure you're familiar with Duck Typing, in particular as espoused in the Ruby world: "If it walks like a duck and quacks like a duck, I would call it a duck." Nothing is an unmitigated good, but Duck Typing, or designing against interfaces, is generally a good thing. It allows you to abstract away the implementation details, which is a very good thing in the OO world. One thing missing from Ruby, however, is Dead Duck Typing, i.e. when you cook the duck in the oven, you probably don't want it walking and quacking.

Why wouldn't you just have a different class or object, a "Roast" object that you construct when you kill a duck? Well, you might want to do that, sort of like a "Duck Transfer Object," or DTO. But in some cases, creating a separate object, just so it can be used in a different context, adds unnecessary complexity to a system. Take the example of an accessor in Ruby. I may need to give some other Class the information on how long to cook the duck and at what temperature, but do I need to give that to the pillow manufacturer who is only interested in the feathers?

Paddling away from ducks for a moment, think of the typical business and persistence layers in an application. In the persistence layer, the implementation details need to be exposed, in the business layer, they really shouldn't. In Ruby, you can't hide methods in different contexts, so you end up with cluttered interfaces -- monsters instead of ducks -- that rely on good programmer behavior to prevent tight coupling and low cohesion from creeping in (see the GRASP patterns). Instead, we want High Cohesion, i.e. all of the methods of a Class should focus on one or at most a few responsibilities.

Some will argue this is a Java-ism creeping into Ruby. I say this is just plain old-fashioned good OO design.

Technorati Tags: , , ,

More Evil Inheritance

Tight on the heels of my article on the evils of 'extends' and Scriptaculous, Bernard Sumption, the author of Animator.js, has expounded on why he thinks it is evil and must be destroyed.

All of the pain caused by inheritance can be traced back to the fact that inheritance forces 'is-a' rather than 'has-a' relationships. If class R2Unit extends Droid, then a R2Unit is-a Droid. If class Jedi contains an instance variable of type Lightsabre, then a Jedi has-a Lightsabre.

The difference between is-a and has-a relationships is well known and a fundamental part of OOAD, but what is less well known is that almost every is-a relationship would be better off re-articulated as a has-a relationship.

As I've already pointed out, composition is to be preferred over subclassing in most cases, and that the GoF patterns are all about replacing implementation inheritance (extends) with interface inheritance (implements). Combine this with Larman's GRASP patterns, and you see that much of the thrust of OOAD is about working around the limitations of "extends."

Technorati Tags: , , ,

Scriptaculous and Why ‘extends’ is Evil

The extends keyword is evil—maybe not at the Charles-Manson/Vlad-the-Impaler level, but bad enough that reputable designers don't want to be seen in public with it. The Gang-of-Four Design Patterns book is, in fact, largely about replacing implementation inheritance (extends) with interface inheritance (implements).

-- Allen Holub, Holub on Patterns: Learning Design Patterns by Looking at Code

Holub can be a bit controversial in OO circles. He throws bombs like "getters and setters considered harmful." Not everyone likes or respects him, but beneath some of that hyperbolic language, he makes some good points. Some of the arguments he makes about OO in general, and Java in particular, can easily be applied to the world of JavaScript and Ajax libraries.

Take Scriptaculous and Prototype, for example. Because JavaScript is missing some of the syntactic sugar for traditional declarative OO programming, many utility libraries take as their first task the creation of functions that make creating class hierarchies much easier. With this tool in hand, like a novice Java or C++ programmer on a bender, everything is inheritance. Everything.

Now I like using Scriptaculous, but Object.extends makes far too many appearances in it for my taste. Pretty much every effect is implemented by extending Effect.Base. The only exception is Effect.Parallel, which allows you to compose two simple effects. The resulting code is somewhat messy and difficult to modify, since the design mixes two different concerns in a single object: the scheduling of the effect and the actual DOM modification that achieves the effect.

Having started the porting of Scriptaculous to GWT (GWTaculous), I was very tempted to replace inheritance with something like the Command pattern, essentially composing the scheduling part of the effect with the DOM modification part, as mentioned above.

Right now, changing Effect.Base is extremely difficult, as doing so would break all of the effects subclasses (the Fragile-Base-Class problem, as Holub calls it). A clearly defined command interface would simplify that immensely.

There is good news on the horizon, however. Some JavaScript/Ajax libraries are starting to show a little more OO sophistication. Take Ext JS. In Ext JS, the behavior of widgets and components can be modified through the composition of different objects. To have a data grid widget, for example, retrieve it's data from a file, a static JSON structure or an Ajax call, all that is necessary is to pass an appropriate object to the widget that implements a well-defined interface. No extends necessary. Nice.

So, when writing frameworks or even a large application or library in JavaScript, view extends with mistrust. Most times, there is a better (in OO terms) way.

Technorati Tags: , , ,

YUI Bubbling Library: a seriously cool design pattern

Caridy Patino recently posted to the YUI Blog about his event-bubbling library, which uses the subscriber/publisher design pattern to abstract an entire webapp's event binding into its own unobtrusive behavioral layer. Instead of attaching events to individual DOM nodes using addListener, you intercept and process all events near the document root, then use CSS classes or other criteria to match up individual events with the correct handlers. In effect, you end up with a big, global switch statement for handling mouse clicks, mouseovers, keydowns and other events.

Patino, a respected contributor to the YUI mailing list, makes a strong case for the usefulness of his library on larger, more event-driven webapps. For one thing, it can reduce the overhead of handling IE memory leaks. For another, it can simplify the process of attaching custom JavaScript behaviors to dynamically loaded content. Best of all, it can be used to improve performance of really complex apps.

Of course, such an abstract approach isn't for every developer or every application. Patino is pretty frank about both the pros and cons of his approach for specific situations. Even if the actual technique isn't for you, though, the post is a fantastic primer on the intricacies of DOM events and the publisher/subscriber pattern.

Developer’s Notebook: Useful OO JavaScript resources

My post about learning to organize classes without the semantic sugar of Prototype earned me some wide-ranging comments here and on Ajaxian. My favorite was Isaac Z. Schlueter Matthew Smith's proposal of a new framework: JLJ (Just Learn JavaScript). To that end, I thought I'd compile some of the most useful sites and posts I've come across in my quest over the last couple of years to employ better inheritance strategies in my JavaScript.

Let's face it, in the wide world of web development, for every
dedicated client-side developer with a real taste for JavaScript, there
are 10 Java middleware developers who believe that JavaScript isn't a
"real" object-oriented language. Programmers with a broad range of
experience in a wide array of languages will argue that JavaScript's
loose typing, dynamic nature and prototype-based inheritance scheme are
actually far more "object-oriented" than, say, Java or C++. That may be
true, but there are lots of folks out there writing production code who
have never written complex software using any language _but_
JavaScript. For these folks, myself included, JavaScript's dynamism is
both a blessing and a curse. There's a lot of freedom, but not a lot of
guidance. Languages that rely on good developer
behavior rather than the intrisic properties of the language themselves
can be dangerous. Just enough rope to hang yourself, and all that jazz. For those of us whose primary language is JavaScript, a little structural guidance can help a lot.

As the inestimable Douglas Crockford illustrates in Classical Inheritance in JavaScript, the main benefit to inheritance in a dynamic language is re-use. Most of us are interested in getting the most mileage possible out of every line of code we write. Many JavaScript frameworks enforce or encourage a particular method of doing this; most are modeled on the classical inheritance schemes of other languages. Every serious student of JavaScript should learn the strengths and weaknesses of these patterns - and how to implmenet them on the fly, without a framework to fall back on.

A note on this list: It's a highly subjective smattering of articles I found useful. Some are high-level discussions of JS itself, or of inheritence strategies in general. Others grapple with the interitance models of specific libraries in ways that highlight the underlying issues. I could post a completely separate list of JS/Ajax frameworks and their various approaches to the topic. But that's a different post for a different day.

On to the list:

Inheritance Strategies

Closures, the Global Namespace and the Module Pattern

Singletons, Lazy Constructors and Memoization

Further Reading: DSLs, Aspect-Oriented Programming and More

Leaky Business Data and Logic with GWT

Sometimes architectural concerns dictate design. That can mean abandoning an elegant approach for something more old school. Take for example the case of GWT-based webapp vs one implemented with vanilla JSP's. The presentation tiers differ in a number of ways, most significantly in who controls the execution environment. In the case of the JSP, you control it (unless someone hacks in). In the case of the GWT interface, the end-user controls it. This consideration forces our hand with regard to some design decisions.

Let's say we are big fans of the POJO approach, i.e. we want to hand appropriately neutered and spayed domain objects to the presentation tier (managed through a Pojo Facade), rather than trouble with the DTO approach. One technique for exposing the domain objects to the presentation tier (and the business tier) without allowing developers to do too much mischief, is to restrict access via a set of complementary interfaces: the View interface that allows access via nothing but getters; the Bean interface that allow access via both getters and setters, and the Domain interface, that allows access to the domain objects actual business logic related methods.

This three interface has some distinct advantages:

  • The presentation tier can be restricted to just accessing the object through the view/getter interface.
  • ORM libraries and dependency injection (DI) frameworks can use the bean/getter+setter interface
  • The domain objects/business tier can use the domain interface without being tempted to use the getters and setters.

In the case of our traditional JSP presentation tier, we send back view objects. If we take this approach to a GWT-based application, i.e. exposing our domain objects to the presentation tier through a view interface, we end up sending all of the data over to the browser, not just what we wish to expose to the GWT UI. Remember, remember, remember, the browser is not under your control.

Let's take a concrete example. Consider the following naive user comment system.


We load a set of messages and display them in a GWT StackPanel. Below you can see the three interfaces, MessageView, MessageBean, and Message (the business interface) and the fields of the MessageImpl class which also implements the GWT IsSerializable class for GWT-RPC purposes. Note that the email is not exposed to the presentation tier, presumably because we don't want someone spamming our commenters, yet we do want to uniquely identify our users via email for internal purposes.

public interface MessageView {    String getName();    String getSubject();    String getBody();    Date getSubmitDate();}public interface MessageBean extends MessageView {    void setName(String name);    void setSubject(String subject);    void setBody(String body);    void setSubmitDate(Date date); }public interface Message {    boolean hasValidEmail();    boolean hasBadWords();    void cleanMessage();}public class MessageImpl implements IsSerializable, MessageBean, Message {    private String name;    private String subject;    private String body;    private Date submitDate;    private String email;    [...]}public interface MessageService extends RemoteService {    /**     * get a list of messages     * @gwt.typeArgs <client.MessageImpl>

     */    public List getMessages();}

If we now pull up the interface and look at the response from calling the MessageService, we get the following chunk of data:

//OK[1186869290897,7,16,15,14,13,2,1186869290897,7,11,5,4,12,2,1186869290897,7,11,10,9,8,2,1186869290897
,7,6,5,4,3,2,4,1,["java.util.ArrayList/3821976829","client.MessageImpl/65273341","Hell\x20hath\x20no
\x20fury\x20like\x20a\x20developer\x20scorned.","jsmith@mail.com","John\x20Smith","Has\x20Ajax\x20jumped
\x20the\x20shark?","java.util.Date/1659716317","I\x20disagree.\x20Developers\x20are\x20relaxed\x20people
.\n\n>Hell\x20hath\x20no\x20fury\x20like\x20a\x20developer\x20scorned","Bob.Schmidt@angrydev.com","Bob
\x20Schmidt","Re:\x20Has\x20Ajax\x20jumped\x20the\x20shark?","You\x20are\x20so\x20wrong,\x20Bob!!","Ajax
\x20is\x20kewl!!\n\nDon't\x20diss\x20the\x20Ajax,\x20man.","biff@biff.com","Biff\x20Thompson","Jumped
?\x20Ajax\x20is\x20the\x20shark!!"],0,2]

As you can see, the serialized message from the GWT-RPC service contains the super sensitive email addresses, as you would expect. And since the browser's execution environment is not under our control, the email addresses of our forum contributors are exposed to anyone with a copy of Firebug.

This may seem like a dope slap obvious point to most developers. But I've run into this mistake with enough developers to be convinced it has to be pointed out again and again. So, even if you are writing what appears like Java in GWT, be aware of who controls your execution environment. Use DTO's instead that limit the data passed back to just that data you wish to expose.

One downside to using GWT with DTO's is that you can't dynamically generate your DTO's with something DynaDTO. Fortunately you can do reflection in GWT, unfortunately you can only do it at compile time. So right now you have to hand code your DTO's.

Technorati Tags: , , ,

BRE Patterns III: Collaboration Cop, Part II

In explaining this pattern, I wanted to take a step back and explain where and how OO and BRE's intersect. To start with, this excellent post over at Mark Proctor's blog makes the following statement:

Assert all your objects as facts: Rule engines usually know how to handle a fairly heavy load of facts, so let the engine do its magic. If you want to reason over a nested set of objects, assert all of them (not only the top level ones) into the engine and make sure your business model models the relationship between them. After that, writing your rules will be easier and the engine will be able to optimize execution (when compared to using eval and other constructs to access deeply nested structures). Example: if you have an Order fact that contains a list of OrderItems, assert both Order and OrdemItems as facts (if you need to reason over OrderItems too, obviously).

Why, by all that is object oriented, do you have to turn your domain model inside out, exposing what was hidden, unencapsulating what was encapsulated? Isn't this defeating the purpose of object orientation? The answer is, in short, yes. You are defeating the purpose of OO when you expose the innards of your model to the BRE. But it is a tradeoff. You get something for your trouble. Specifically, you get the super efficient rule matching of RETE and it's decendents.

This sort of exploding of the object model happens all the time in systems, and it isn't necessarily always bad. Alen Hollub (author of Why getter and setter methods are evil and other Edsger Dijkstra-like articles) has identified the "procedural boundary layer" and explains it nicely in his book Holub on Patterns: Learning Design Patterns by Looking at Code:

One big exception exists to the no-getter-or-setter rule. I think of all OO systems as having a "procedural boundary layer." The vast majority of OO programs run on procedural operating systems and talk to procedural databases, for example. The interfaces to these external procedural subsystems are by their nature generic. The designer of JDBC hasn't a clue about what you'll be doing with the database, so the class design has to be unfocused and highly flexible. UI-builder classes such as Java's Swing library are another example of a "boundary-layer" library. The designers of Swing can't have any idea about how their classes will be used; they're too generic. Normally, it would be a bad thing to build lots of flexibility that you didn't use because it increases development time. Nonetheless, the extra flexibility is unavoidable in these boundary APIs, so the boundary-layer classes are loaded with accessor and mutator methods. The designers really have no choice.

BRE's are not OO. Yes, the facts can be viewed as objects and the BRE's can be implemented using and OO language and design, but really the internal working of the BRE are most definitely not OO, the more the rule engine knows about each and every object and its innards, the more efficient it can be. Thus the PBL (procedural boundary layer) applies.

As an example why you need to expose all object, consider an order that is made up of line items.

public interface Order {
[...]
void addItem(OrderLineItem item);
boolean removeItem(OrderLineItem item);
[...]
}

Now normally you would hide the details of all the line items inside the class that implements the Order interface. Let's suppose now that we haven't added any of the encapsulated line items to the working memory of the BRE's, just the order. Now let's say we update one of the line items through an operation. The only way we have to telling the BRE that something has changes is by flagging the enclosing Order object. That will trigger a reevaluation of every rule in which the Order plays a part, even ones where the line items play no part.

There are all sorts of ways of dealing with exposing the internals of your domain model to the BRE without breaking encapsulation. One way is to implement both the business interface and a bean interface (getters, setters, etc.) in the implementation (see diagram). The business interface is used within the domain model, the bean interface in the BRE.

BREExample.png

Another approach is to wrap the domain objects in bean containers that access the private instance variables through reflection.

Of course lots of this depends on the specific BRE you are using. Some require you to expose your instance variables directly and don't deal well with method calls. I'd suggest not using those.

Next time I'll go through a simple example using JBoss Rules showing how to convert a domain model to a Collaboration Cop rule base.



Technorati : , , , , ,

BRE Patterns III: Collaboration Cop, Part I

The pattern I'm writing about today -- Collaboration Cop -- is much meatier than the two previous ones, in my opinion. This one is all about transplanting the implicit and explicit business rules of an OO system from its objects to an external BRE.

This is a somewhat involved pattern, and I'll provide some more examples and references in part II. Also in part II, I'll run down the differences between the rule classifications that come out this pattern and the ones you commonly see in works by Ross.

Pattern Name: Collaboration Cop

Synopsis
Extract the business logic that is in an OO domain model -- collaboration rules, property rules and controller logic -- and express it as a set of business rules. Activity in the system is triggered by the UI inserting events into the working memory and firing the rules. Objects can be persisted by something like and ORM framework.

Slightly longer version: if you strip away the user interface and the persistence mechamism, a typical OO application is designed around a domain model and controller or service classes that set object collaborations within the domain model in motion in response to external events. The methods of the controller/service classes often correspond to steps in a Use Case. Embedded in the various domain classes is logic about how object can be modified and accessed, what collaborations can be created or desolved, etc. With this pattern, you extract all the service/controller and validation and collaboration logic into business rules. You populate the working memory with the objects that comprise the context for a Use Case. Finally, in response to an external event, you inject an event object into the working memory and fire the rules that modify the state of the object model (and persist it).

ContextBRE3.PNG
Take the somewhat simplified Use Case where a customer is trying to rent a tape (he's a sucker for punishment and doesn't like DVD's). In a OO system, we would try to create a collaboration as follows (yes, very simplified):

customer.addRental(new Rental(title.getTape()));

The customer object knows how many active rentals a customer has and knows hat he cannot have more than three. This attempted collaboration would throw an exception to indicate that it is not permitted.

In the Collaboration Cop version we would create an event and insert it into the working memory:

VideoStoreEvent event = new VideoStoreEvent();
event.type = VideoStoreEvent.RENT_TAPE;
event.value = "Gone With the Wind";

IF event.type == VideoStoreEvent.RENT_TAPE AND title.getTitle() == event.value AND title.isInStock()
AND customer.activeRentals() < 3
THEN
customer.addRental(new Rental(title.getTape()));
externalObjectSet.add(customer);
externalResponse.message = "Rented tape.";
externalResponse.success = true;
ELSE
externalResponse.message = "Unable to rent tape.";
externalResponse.success = false;

You can wrap a transaction around the sequence of event injections, then save (using an ORM) all of the modified objects in the externalObjectSet.

-----------

This pattern is complex and powerful, and it's implementation is very much dependent on the capabilities of the chosen BRE, how you choose to deal with concurrency, etc.. In part II, I'll also construct a simple example using JBoss Rules.



Technorati : , ,

JBoss Rules Wiki - A Business Rules Community of Practice

The guys over at JBoss Rules are starting to build a little community of practice over in their Wiki.

There's a ton of good stuff over there, including a link to this tutorial by


Technorati : ,

Steps to AJAX Mastery

No, I wouldn't call myself an AJAX master, but, in the words of Laurence Peter, "A man doesn't know what he knows until he knows what he doesn't know." I definitely know what I don't know. And I do know a little (I've been around long enough to have written LiveScript, so I'm old in Internet years if nothing else), so I thought I'd share with you all the Javascript, CSS, XHTML and XSL reading I've done (and haven't done). Maybe you can share your own favorites in the comments.

Yes I've been a big proponent of Component GUI's and writing just Java in developing AJAX applications. Stay in one language and don't mess with CSS, Javascript or XHTML. Reuse the components that others have already written. That way lies productivity. There's only one problem with this approach: who is going to write the widgets and the framework in the first place? Someone has to write Javascript and CSS and XHTML, otherwise nothing will get done. As Billy Preston sang, "nothing from nothing leaves nothing."

So if someone has to write all those widgets, why not you? You know a little Javascript and have written a XPath expression or two. And your girlfriend really liked the CSS you put together for her homepage. So what's stopping you? Well, the truth is that having a passing familiarity with Javascript and the other technologies that make up AJAX is just not enough. Not even close. Your knowledge of Java may actually hurt you in this regard. You have to know this stuff cold to make it sing and dance.

My approach to learning any programming discipline has been as follows:

  1. Read books, the right ones.
  2. Read code, lots of it.
  3. Write code, lots of it.

The Right Books

Where to start? Picking up a tome like Ajax in Action Ajax in Actionseems like a good place to start, but it's really just a crash course in those fundamental technologies you'll need, sort of like skipping over Calculus to take Algebraic Topology as a freshman, or, for those non-math geeks, trying to get a job in Paris after only one lesson in French. You need a better grounding.

In my opinion, the right place to start is by understanding the browser. That's because Javascript has two parts to it: Core and Client-Side. Client-Side is all of the browser specific stuff, so if you try to learn Javascript without understanding the browser, it's just jibberish. Get to know all you can about CSS and XHTML and XSL before you tackle Javascript and you'll save yourself a lot of pain.

I recommend starting with XHTML first, then move on to CSS. (The problem with some of the better books, as you'll find, is that they're a bit long in the tooth, i.e. they have publication dates from as far back as 2001.)Head First HTML with CSS & XHTML (Head First)

None of the books that I learned on for HTML/XHTML are still relevant. The fifth edition of the O'Reilly book HTML & XHTML: The Definitive Guide is so out of date and focused on old browser quirks that it's a sheer waste of time. My instinct is to stay away from something like the CSS and XHTML combo Head First book. At 658 pages, you'll be well into next year by the time you've read it all. As you'll find out, you've got plenty of reading to do. Plus the whole Head First series is annoying to read. Still, I'm not sure I have any better suggestions. Until AJAX came along, browser technology was considered uninteresting, so nobody published in that category.

 

CSS Mastery: Advanced Web Standards Solutions (Solutions)For CSS I'd recommend two books: Cascading Style Sheets: The Definitive Guide and CSS Mastery: Advanced Web Standards Solutions. The second is a more advanced text, so read it after working through the first. You may also want to supplement your reading with CSS examples from the CSS Zen Garden. Also check out Open Source Web Design for some 1600+ examples. Finally, Position is Everything is likely to have more recent updates on browser quirks than any book you are likely to buy.

For XML/XSL, I'd recommend an old text (originally a Wrox book, now put out by APress): Beginning XSLT. Get the first one, not the 2.0 book. The examples in this book are not for the browser, so you'll also need some more info on how to do it in Javascript. For this, look to Professional JavaScript for Web Developers. Chapter 15 is probably the best intro to the topic in print.

Finally we've arrived at Javascript, for which I have two recommendations. The latest edition of the JavaScript Bible by Danny Goodman is still the definitive work. The other book is JavaScript Bible, Fifth Editionthe ancient JavaScript: The Definitive Guide by David Flanagan. The latest edition is from 2001, but it really is the only book that deals with Javascript the language.

Only now that you've swallowed these tomes whole are you ready to move on to the Ajax in Action book. All those bits of jargon that were confusing before are now old hat. This book will fill in some of the missing pieces around XHR that those other Javascript books left out.

Now I've left out lots of other books that are useful and should probably be required reading. You should probably bone up on OOAD, an Operating System or two, a server-side development language, networking, etc.. My intent here was to give you a minimal set of books, not an exhaustive one. Even the books that I have recommended could be considered to be exhausting if not exhaustive. Anyone keeping score will have noticed that these books clock in at over 5700 pages. That's a lot of reading. That huge page volume, however, is simply a reflection of the fact that you are learning four different languages and combining them all together. Maybe you don't have to read all of those page, but even half that number is a commitment to many nights at home. I wish I could recommend small 100 page books on each subject that are more than simple "Hello World!" pamphlets. If anyone is aware of any, please let me know.

Reading Code

Books will only tell you so much. To really get a feel for how things are done -- best practices, so to speak -- you have to read code. Preferably good code. Avoid generated code like that produced from Tibco GI or GWT. Stick to hand-coded Open Source stuff like Prototype, Scriptaculous, Dojo and the like. At this point you'll probably know enough to decide for yourself what to read. There's a good book on how to read code, but I'll spare you another tome.

Make sure to get some tools so you can read and debug the code. I personally like the Firebug for spelunking around the DOM and Javascript, but there's a whole list of other tools available over at ajaxpatterns.org.

Writing Code

Now, five years later, you are ready to start writing some code. Use what you've learned. Good luck.

Example GWT App - Newsletter Signup

I decided to try out GWT on a simple project: providing a small newsletter signup box on a conference micro site. The idea was that after checking that a valid email had been submitted -- and complaining with a DHTML popup if it wasn't -- that email would be sent to a backend web service (asynchronously, of course). While the async XHR request was percolating, the newsletter box would display a thank you message, then fade away. A cookie would also be set, preventing the newsletter box from displaying during the lifetime of the browser session.

This just barely qualifies as AJAX, since I'm doing just one crummy little "Hello World!" communication with the backend. Still, it gets rid of the whole painful navigation to a signup screen, so that's a win in the AJAX column.gwt_example.jpg

OK, so just 150 lines of code later (yeah, I know), I have my little box. The site is software500.pathf.com where you can see the newsletter box in the bottom right corner. Please be kind and don't sign up your goofy friends.

 

A few lessons from the excercise:

  • GWT doesn't remove the need for Javascript. I found myself writing a few funky methods like this:
     public native void setCookie(String cookie, String value) /*-{    document.cookie = cookie + "=" + escape(value) + ";Path=/"; }-*/;         public static native String getLocationHref() /*-{    return $wnd.location.href; }-*/; 
  • The GWT documentation is not complete. What is does talk about is pretty solid, but the fact that Google is not a shrinkwrap software company is pretty evident. Let's hope they hire some gifted technical writers and such for the general release of GWT.
  • Debugging in the hosted mode is pretty handy. Not that an application of this simplicity needed a whole lot of debugging.
  • One of the gaps in documentation is that it isn't very task based. Suppose you have a question like "How do I include a third party jar file?" You can dig through the documentation site and maybe come accross an explanation of the syntax of the MyApp.gwt.xml file and on another page the directory structure of a GWT project. Putting the two together takes a bit of noodling. That's definitely a steep start to the learning curve that doesn't need to be there.
  • Spend some time with the more essoteric parts of the documentation, like how to write modules. Also, take a spin through the gwt.js file and see how it parses the gwt meta tags. This will ease your pain down the road when your GWT app and html page sit in different directories.

In my previous article on GWT Developments, I've pointed out several good resources for getting started, including the GWT newsgroup. Make liberal use of them.

AJAX and the Zeigarnik Effect

My colleague Bob Moll over in the UXD blog writes about the Zeigarnick Effect and it's implication for designing GUI's. What is the Zeigarnick Effect? Bluma Zeigarnick was a Russian psychologist who in the 1920's discovered that we remember unfinished tasks much better than completed ones. This memory comes from a psychological pressure to complete unfinished tasks.

Bob notes that in a rich GUI, the psychological pressure is to detour and finish short tasks, leaving a trail of longer, unfinished tasks. He suggests that we include a facility for a queue of unfinished tasks in applications so that users can easily go back and finish them.

In the web application world, we avoided this aspect of the Zeigarnick Effect by making it difficult if not impossible for the user to diverge from the page flow. Now, with the capability to use fancy modal dialogs that interact with the server, we can add optional subtasks into the flow. AJAX-powered command completion helps prevent the the user wandering off in another window to search for the right thing to enter. My favorite example is the WSJ's selection-based search, which avoid interrupted reading to search for another term.

As you design your applications, give some thought to the Zeigarnick Effect and how you can use AJAX to smooth the continuation of interrupted tasks.

MVC and RIA - Learning From Desktop Apps

Whether you're writing AJAX applications using enhancements to existing webapplication frameworks or adopting the new component GUI approach, you as a developer are faced with a new granularity of events. Where before you had the monster postback, now you must respond to mouse clicks, key presses, menu selections, etc.

On top of this, with a single page interface, you may have many more controls on the page. This brings on the problem of context, i.e. that not all of these controls are appropriate for a particular context such as when a particular part of a table or list box is selected or when the focus is on a particular window.

The above just scratches the surface of the sorts of challenges that you'll discover writing RIA's with AJAX technologies. The good news is that there are already solutions in place since these are the sorts of problems that desktop GUI developers face all of the time. For example:

  • Enabling and disabling menus and other controls can be done using the State pattern. A collection of state objects would be used to enable and disable the controls as appropriate.
  • Many of the component GUI frameworks implement an Observer pattern for event management. UI events come in now in little bites instead of one huge request and can be consumed by listeners that wait on a specific component.
  • MVC needs an upgrade when you're dealing with big heirarchies of components. Combining the Composite and Chain of Responsibility design patterns, you get the Heirarchical MVC (HMVC) pattern. (If you've worked with WebWork you may have run across the "Pull HMVC" pattern. That heirarchy refers to the model, not the whole MVC.)
  • The Command pattern is often used to implement undo.

That's just a sampling of desktop GUI solutions you can make use of. What can you do to expand your solution space for RIA's? Read lots of code. Find as many good open-source desktop GUI's as you can and read their code. You'll find ways of doing things that don't resemble the typical webapp approach. Here are a few to get you started.

Resources:

  • The Spring Rich-Client Project. Based on the Spring Framework. Used for buidling desktop GUI's. Read the code and get a sense for how to build your RIA framework. Good source for ideas
  • The Scope Framework. The bad new is that this is a desktop GUI framework based on Swing that hasn't been updated since 2002. The good news is that this is a great place to read some code and learn how to develop component GUI applications.
  • The HMVC Framework from Crionics. Again, no longer maintained, but a great place to read some code.
  • Tutorial (in C#) on implementing undo with the Command pattern.
  • A discussion of the Presentation-Abstraction-Control (PAC) architectural pattern. This one is just as old as the MVC pattern, but since the MVC pattern was intended for simple interfaces it was also simpler to implement. Thus MVC won out even in cases where PAC is more appropriate, such as with more complicated UI's.

Update 1: Oliver Steele has an excellent overview of MVC as it exists in the desktop, webapp and RIA worlds. He points out why non-RIA, i.e. traditional webapp programming is so tough:

That complexity includes the real world application of what are still
research topics in academia: staged programming for multiple-target
code generation (Mac IE, Windows IE, Netscape, Mozilla, Safari, Opera),
process migration, and (usually manual) CPS conversion to maintain program state across pages.  No wonder web programming is hard!

Well worth a look.

COMET: Socket Hungry AJAX

From back in late March, Alex Russel over at IrishDev writes about a new AJAX technique, calling it COMET. What is COMET? Basically the browser makes a request of the servers, but the server keeps the socket open over a long period of time.

[COMET applications] all use long-lived HTTP
connections to reduce the latency with which messages are passed to the
server. In essence, they do not poll the server occasionally. Instead the server has an open line of communication with which it can push data to the client.

Does it scale? We've talked about this stuff before when we spoke about Jetty Continuations. I wrote then that

I don't like this method because it is wasteful in terms of sockets and
threads; also, it is likely to stress stateful firewalls, load
balancers, etc., and may break in lots of client environments.

I stand by that statement. Beyond the issue of migrating these connections between nodes in a load-balanced cluster (yes, you could close the connection and have the client automatically reopen the connection), there are serious scaling issues.

One of the things that made HTTP based applications scalable was that they made use of small, stateless requests. This meant you could handle requests from an order of magnitude or more users than a comparable stateful application.

It's true that the typical AJAX polling for async updates also puts a burden on the server, firewall, load balancers, etc., but that depends partly on the frequency of the polling and the number of clients doing the polling. Even if I have 10,000 users polling the server every half second, I may still only have a few hundred sockets open at any one time if the request/response size is small and the user's network latency is low.

Modifications to server software like Apache and Jetty to conserve resources like threads and make use of IO multiplexing is a first and probably necessary step. Maybe I'm making too much of this stateful thing. We may have so much application state information floating around on the server side anyway that is will dwarf any OS and network resources that COMET and related technologies seek to spend.

Update 1: DWR's next release should have an implementation of COMET that they are calling "Reverse AJAX." More interesting, however, is the fact that they are releasing an API that allows one to write Javascript by writing Java.

About Pathfinder

  • We design and build extraordinary applications for companies looking to make the next great idea a reality.
  • learn more

Topics