Using Revealing Module Pattern with Web Interface Design

I recently joined a project that required me to develop a mobile website for the client. We already had a fully functional desktop version of the website. There were around 10000+ lines of JavaScript code for the existing desktop website and most of it was not at all reusable for the mobile website. The purpose of this blog post is to identify what went wrong with the original design of the JavaScript code and to provide a solution that could have saved around two to three weeks of (re)work.


The Problems

Following are some issues that made us re-implement the complete functionality from scratch. Later the approach and guidelines that we implemented to avoid the same problem again will be discussed.

JQuery (mis)usage
Many methods implementing some business logic were used $(‘#id’) to access values. To reuse this code, I’d have had to use exactly same id/classes for elements.

Too many document.ready()
Each script included on the page had its own document ready handler. Multiple entry points made it hard to determine the flow of code.

Modular approach
The whole JavaScript code was organized as global functions. Need I say more?

Code Repetition
At some places, very similar or even the same functionality was implemented in different functions. Validation and error handling code was also repeated at a number of places.

Repeated element ids

Same elements id were used at a number of places.

What Affects What?
It was hard to determine which piece of code was intended for which part of the page. Some JavaScript files were being used on multiple pages. There each page was broken into several jspx files that may or may not be included on the page depending on some business logic. Also, some of those jspx had conditions of their own to add or skip some elements.

The Required Solution

Now that we have looked at the major problems with the existing JavaScript code, let’s take each of the problems and see what we can do to avoid them.
JQuery (mis)usage
To fix this, we needed to separate the business logic from UI logic. E.g. code to update user information on server should not be defined in the click handler of the submit button. We should, instead, put the ajax call in a separate function, taking the user details as parameters. The click handler should gather user details from form elements and pass them to the function. Similarly, use callbacks to update UI when a response is received from the server.

In UI code, we should be able to somewhere define ids of various form fields instead of hard coding field ids everywhere.

Too many document.ready()  
There should be only one script with document ready handler, and it should be responsible to initialize various modules used on the page.
Modular approach & What affects what?
We needed an object oriented approach with business and UI logic in separate modules. Also, we needed some sort of mapping between the UI modules and jspx files. This would make it easier to determine exactly what code needs to be updated if something changes on the UI.
Code repetition
We needed to organize modules neatly. The business logic modules should have some sort of hierarchy based on functionality. The UI modules should maintain same hierarchy as the back end jspx files.
The validation and error handling code should be moved outside business and UI logic, in separate modules of their own.
Repeated element ids
It was simple to use unique ids in a single jspx file. However, on a completely rendered page we could still have repeated ids, especially when a jspx file was included more than once on a page. So, while inserting a jspx file, we also needed to wrap it inside a div container with unique id. We also needed some approach to be able to identify each element without specifying complete id-hierarchy.

Coding/Design Guidelines

To implement the changes suggested in the previous section, I had to write some utility modules to handle things such as validation, error handling, a JQuery wrapper to transparently access DOM elements with full id etc.

Following are some design and coding guidelines that I followed while implementing the mobile website.

Jspx Design Guidelines

  • Every id in a jspx file should be unique.
  • Every jspx file should be included inside a div container of its own; the container should be given a unique id in the jspx file.
  • All form fields should use a common markup style at all places e.g. each field should be placed inside a div container with proper classes such as ‘textbox’, ‘disabled’, ‘read-only’ etc

JavaScript coding guidelines

  • Organize the code in some meaningful namespaces, clearly separating business logic, UI logic and form validation and error handling code.
  • None of the code in business logic must interact with UI. Any of the business logic functions must accept required data and callback functions as arguments.
  • The business logic modules should be singletons unless it is required to create multiple objects of the module.
  • A UI module should be created for each jspx file.
  • For each jspx file included, a module must create objects of each of the module respective to included jspx files.
  • Any HTML element should be accessed only by its respective module.
  • While creating a child UI module, the parent module must pass the full id of its child jspx’s container div to the child module.
  • Define all form fields and HTML elements of the respective jspx accessed in the module.
  • While accessing any field by id in a UI module, the field id should be appended to the full id of the container div passed by the parent module. (We implemented a utility module to transparently handle this).
  • Define callbacks in each UI module for any event that might be interesting to the parent module.  e.g. submitButtonClicked, someCheckBoxChecked etc.
  • In case a child module needs to update parent module for some event, it must do so via callbacks. The parent module needs to set these callbacks at the time of creating the child module object.
  • Define public functions for actions requested by parent module. e.g. enableSubmitButton(), showSomeHiddenElement() etc.
  • In case a parent module needs to update UI for a child module, it must do via public functions exposed by the child module.
  • Don’t access HTML element attributes directly. For example, to hide elements don’t change display style. Create CSS classes for each required state of HTML elements and add/remove these classes to update any
  • Avoid creating id based CSS rules and using classes in JavaScript.
Summing up everything, the following is what we achieved by using the new approach for developing the mobile website:
  • The business logic is now completely separate from the UI code, and can be used independent of UI code.
  • The UI code has direct mapping with the jspx files. If a jspx file is modified, only its respective is modified.
  • Since all fields and HTML elements are defined in each module, changing ids of fields in jspx file requires just a single update in its module.
  • All JQuery dependent code has been moved to the ModuleHelper module. Although it might still require a lot of other changes, replacing JQuery with any other library requires minimal UI code changes.
  • Each HTML element is now uniquely identifiable by its module, even if the jspx file gets included multiple times on the same page.
  • Form validations and error handling are now completely removed from the UI code.

Further Reading:

Following are a few links for further reading on some basic JavaScript features and design patterns:
Functions in JavaScript are First Class Objects
JavaScript Closures
JavaScript Design Patterns

Building Web Services with JAX-WS : An Introduction

Developing SOAP based web services seem difficult because the message formats are complex.  JAX-WS API  makes it easy by hiding the complexity from the application developer. JAX-WS is the abbreviation for Java API for XML Web Services. JAX-WS is a technology used for building web services and clients that communicate using XML.

JAX-WS allows developers to write message-oriented as well as RPC-oriented web services.

A web service operation invocation in JAX-WS is represented by an XML-based protocol like SOAP. The envelope structure, encoding rules and conventions for representing web service invocations and responses are defined by the SOAP specification. These calls and responses are transmitted as SOAP messages over HTTP.

Though SOAP messages appear complex, the JAX-WS API hides this complexity from the application developer.  On the server-side, you can specify the web service operations by defining methods in an interface written in the Java programming Language. You need to code one or more classes that implement these methods.

It is equally easy to write client code. A client creates a proxy, a local object representing the service and then invokes methods on the proxy. With JAX-WS you do not generate or parse SOAP messages. Thanks to JAX-WS runtime system that converts the API calls and responses to and from SOAP messages!

With JAX-WS, web services and clients have a big advantage which is the platform independence of the Java programming language. Additionally JAX-WS is not restrictive: a JAX-WS client can access a web service that is not running on the Java platform and vice versa. This flexibility is possible because JAX-WS uses technologies defined by the World Wide Web Consortium – HTTP SOAP and the Web Service Description Language or WSDL. WSDL specifies an XML format to describe a service as a set of endpoints operating on messages.

Three most popular implementations of JAX-WS are:

Metro: It is developed and open sourced by Sun Microsystems. Metro incorporates the reference implementations of the JAXB 2.x data-binding and JAX-WS 2.x web services standards along with other XML-related Java standards. Here is the project link: You can go through the documentation and download the implementation.

Axis: The original Apache Axis was based on the first Java standard for Web services which was JAX-RPC. This did not turn out to be a great approach because JAX-RPC constrained the internal design of the Axis code and caused performance issues and lack of flexibility. JAX-RPC also made some assumptions about the direction of Web services development, which turned out to be wrong!

By the time the Axis2 development started, replacement for JAX-RPC had already come into picture. So Axis2 was designed to be flexible enough to support the replacement web services standard on top of the base framework. Recent versions of Axis2 have implemented support for both the JAXB 2.x Java XML data-binding standard and the JAX-WS 2.x Java web services standard that replaced JAX-RPC(JAX-RPC: Java API for XML-based Remote Procedure Calls. Since RPC mechanism enables clients also to execute procedures on other systems, it is often used in a distributed client-server model. RPC in JAX-RPC is represented by an XML-based protocol such as SOAP). Here is the project link:

CXF: Another web services stack by the Apache. Though both Axis2 and CXF originated at Apache, they take very different approaches about how web services are configured and delivered. CXF is very well documented and has much more flexibility and additional functionality if you’re willing to go beyond the JAX-WS specification. It also supports Spring. Here is the project link:

At Talentica we have used all the three implementations mentioned above in various projects.

Why CXF is my choice?
Every framework has its strengths but CXF is my choice. CXF has great integration with the Spring framework and I am a huge fan of Spring projects. It’s modular and easy to use. It has great community support and you can find lots of tutorials/resources online. It also supports both JAX-WS and JAX-RS specification but that should not be a considering factor while choosing CXF. Performance-wise it is better than AXIS and it gives almost similar performance when compared to Metro.

So CXF is my choice, what is yours?

Multi-server Applications on the Wireless Web

Here we will discuss how we can build Web applications that can serve wireless clients according to client capabilities.

What are the challenges?
Development of mobile applications is often highly dependent on the target platform. When developing any mobile content portal we generally think about the accessibility of that portal through the mobile browsers (like Nokia, Openwave, i-mode browsers, AvantGo in PDA etc) which generally use markup languages like WML, HDML, cHTML, XHTML etc. We want to ensure that the browser gets the compatible markup language and can present the portal content in correct format. In short, creating a wireless application that works on as many devices as possible is not difficult, it’s useless. If you invest a huge amount of resources today, chance are that a new device will be shipped tomorrow and you‘ll need to tweak your application again.

What is the solution?
Wireless Universal Resource File (WURFL) is an open source project that uses XML to describe the capabilities of wireless devices. It is a database (some call it a “repository”) of wireless device capabilities. With WURFL, figuring out which phone works with which technology is a whole lot easier. We can use the WURFL to figure out device capabilities programmatically and to serve different content to different devices dynamically, depending on the device accessing the content.

Here are some of the things WURFL can help you know about a device:

  • Screen size of the device
  • Supported image, audio, video, ringtone, wallpaper, and screensaver formats
  • Whether the device supports Unicode
  • Whether it is a wireless device? What markup does it support?
  • What XHTML MP/WML/cHTML features does it support? Does it work with tables? Can it work with standard HTML?
  • Does it have a pointing device? Can it use CSS?
  • Does it have Flash Lite/J2ME support? What features?
  • Can images be used as links on this device? Can it display image and text on the same line?
  • If it is an iMode phone, what region is it from? Japan, US or Europe?
  • Does the device auto-expand a select drop down? Does it have inline input for text fields?
  • What SMS/MMS features are supported?

WURFL framework also contains tools, utilities and libraries to parse and query the stored data in WURFL. WURFL API is available in many programming languages, including Java, PHP, .Net, Ruby, and Python. Various open source tools are build around this WURL – HAWHAW(PHP), WALL(Java) , HAWHAW.NET (.Net framework) , HawTag (JSP Custom tag library etc).

How does WURFL work?
When a mobile or non-mobile web browser visits your site, it sends a User Agent along with the request for your page. The user agent contains information about the type of device and browser that is being used. Unfortunately, this information is very limited and at times is not representative of the actual device. Using WURFL API, the framework then extracts the capabilities associated with that device. Based on the device capabilities, the framework creates the dynamic content – WML, HTML, XHTML etc.

Though there is concern with the extra latency time taken due to user-agent look up, it’s worth to use it looking at its advantages. One of the biggest advantages is regarding a new device if and when it enters the market, we will not need to change our application, but just update the WURFL to keep the application optimized. It is very simple and the architecture is sound. Go for it!!!