Home > Articles > Programming > Java

📄 Contents

  1. 6.1 General Practices
  2. 6.2 A Multitude of Simple Interfaces
  3. 6.3 Dense, Rich Interfaces
  • Print
  • + Share This
This chapter is from the book

6.2 A Multitude of Simple Interfaces

When an application calls for many different interfaces, each offering a different set of functionality, the interfaces should load only as much of the available function library as necessary. This practice keeps each page load light and fast, even as the application and its data grow. Once loaded, each page can load additional data and functionality as needed; these requests will return as lightly and as quickly as the initial page load itself.

6.2.1 Modularity

To keep a library flexible enough to support many different interfaces that offer a variety of functionality, each piece of that functionality needs to exist independent of the rest. The pieces can extend an object from a core set to make it easier to offer a consistent object interface without duplicating code.

Throughout this book, classes continually extend other base classes. This not only brings the advantages of object-oriented programming to the applications and code samples, but also makes it much easier to load each set of functionality as necessary. For example, the following JavaScript classes exist in effects.lib.js, but extend the EventDispatcher class:

 * The base class of all Effects in the library
function Effect() { }
Effect.prototype = new EventDispatcher;

 * Kind of useless by itself, this class exists to get extended for
 * use with text, backgrounds, borders, etc.
function ColorFade() { }
ColorFade.prototype = new Effect;
// Triggers at the start and end of the effect
ColorFade.prototype.events = {
    start : new Array(),
    end : new Array()
// Default to changing from a white background to a red one
ColorFade.prototype.start = 'ffffff';
ColorFade.prototype.end = 'ff0000';
// Default to a second, in milliseconds
ColorFade.prototype.duration = 1000;
ColorFade.prototype.step_length = 20;
// The current step (used when running)
ColorFade.prototype.step = 0;
// Reference to the interval (used when running)
ColorFade.prototype.interval = null;
// Calculated values used in color transformation
ColorFade.prototype.steps = 0;
ColorFade.prototype.from = null;
ColorFade.prototype.to = null;
ColorFade.prototype.differences = null;
ColorFade.prototype.current = null;
 * Parse a three- or six-character hex string into an
 * array of hex values
ColorFade.prototype.explodeColor = function(color) {
    // Three or six, nothing else
    if (color.length != 6 && color.length != 3) {
        throw 'Unexpected color string length of ' + color.length;

    var colors = new Array();
    if (color.length == 3) {
        colors[0] = parseInt('0x' + color.charAt(0) + color.charAt(0));
        colors[1] = parseInt('0x' + color.charAt(1) + color.charAt(1));
        colors[2] = parseInt('0x' + color.charAt(2) + color.charAt(2));
    } else {
        colors[0] = parseInt('0x' + color.charAt(0) + color.charAt(1));
        colors[1] = parseInt('0x' + color.charAt(2) + color.charAt(3));
        colors[2] = parseInt('0x' + color.charAt(3) + color.charAt(5));
    return colors;
 * Executes the fade from the start to end color
ColorFade.prototype.run = function() {
    this.from = this.explodeColor(this.start);
    this.to = this.explodeColor(this.end);
    this.differences = new Array(
         this.from[0] - this.to[0],
         this.from[1] - this.to[1],
         this.from[2] - this.to[2]

    // Steps in portions
    this.steps = Math.round(this.duration / this.step_length);
    // Reset the step so that we can run it several times
    this.step = 0;

    this.interval = setInterval(this.runStep, this.step_length, this);

    // Success!
    return true;
 * Called from an Interval, runStep takes what this should resolve
 * to and references it
ColorFade.prototype.runStep = function(dit) {
    var state = (dit.step / dit.steps);
    dit.current = new Array(
         dit.from[0] - Math.round(state * dit.differences[0]),
         dit.from[1] - Math.round(state * dit.differences[1]),
         dit.from[2] - Math.round(state * dit.differences[2])
    if (dit.step == dit.steps) {

The ColorFade class serves as the base of all color-fading classes, offering a consistent interface. All of these effects exist in the same library, so that the application can load them as necessary, rather than at load time. In this way, simple interfaces that do not require the functionality can spare the user the loading time for unnecessary libraries.

In fact, the class definitions would also allow for a particularly intensive effect to exist in a separate, optionally loaded library. This would mean that the interface would have even more of an ability to load only the required functionality for the interface in question, and the load time could stay even smaller.

This modularity has just as great an impact on the server-side application as it has on the client. From the server application, the more power the application has over the choice of resources to load, the more precise the libraries loaded and the faster the response returns from the server. Even if the server-side application has thousands of paths that it can take for properly handling a response, it still can use efficient lookup tables for loading only the necessary modules and returning them quickly, no matter how much available functionality the application has to offer.

On the client side, this technique keeps the memory usage low even for complex applications, as the application moves from interface to interface, removing the unused libraries from memory and loading in the classes and functions it needs for the next step in the application. By loading in these libraries after the initial page load, the client-side application can keep even full page loads fast and responsive. It need only manage the timing of the additional library loads properly so that the user does not need to wait an unreasonable amount of time for the next piece of the interface to load.

6.2.2 Late Loading

Once an interface initially loads, it can offer the most commonly used functionality from the already available resources. This functionality should cover the most typical interaction scenarios, but should not restrict the users to only that small set of functionality. By loading additional functionality as needed, the interface can support applications as light and simple or complex as the user needs for that particular instance, without bogging down the loading time of the page itself.

The following code enables the application to late load code in two ways. It allows the inclusion of known classes by calling Utilities.include("ClassNameHere", callbackWhenIncluded), which uses a simple lookup to load the appropriate file for a given class. It also allows the inclusion of arbitrary files by calling Utilities.loadJavaScript("filename.js", callbackWhenLoaded);, which can load internal or external JavaScript files. Both of these methods take an optional callback argument, which receives a single Boolean parameter of true when successfully loaded, or false when the load failed due to a timeout or some other issue:

 * A list of available classes, as keys to their
 * corresponding source files. A script should
 * pre-generate this list rather than having it
 * hard-coded, so that it could always have the
 * latest classes and files.
Utilities.classFiles = {
    "AjaxEvent" : "includes/ajax.lib.js",
    "AjaxRequest" : "includes/ajax.lib.js",
    "AjaxRequestManager" : "includes/ajax.lib.js",
    "BackgroundFade" : "includes/effects.lib.js",
    "ColorFade" : "includes/effects.lib.js",
    "Controller" : "includes/main.lib.js",
    "CustomEvent" : "includes/ajax.lib.js",
    "Effect" : "includes/effects.lib.js",
    "ElementEffectEvent" : "includes/effects.lib.js",
    "EventDispatcher" : "includes/ajax.lib.js",
    "FadeEvent" : "includes/effects.lib.js",
    "Field" : "includes/main.lib.js",
    "ForegroundFade" : "includes/effects.lib.js",
    "Messenger" : "includes/main.lib.js",
    "Model" : "includes/main.lib.js",
    "Throbber" : "includes/main.lib.js",
    "Utilities" : "includes/main.lib.js",
    "View" : "includes/main.lib.js"
 * Late-loading of JavaScript files based on object to
 * file lookups. Once the file loads (or times out), it
 * triggers the callback (if specified), passing a Boolean
 * indicating whether it successfully loaded.
Utilities.include = function(class, callback) {
    // First, if already loaded, just call the callback
    if (window[class]) {
        if (callback) {
            setTimeout(callback, 10, true);
        return true;
    } else if (Utilities.classFiles[class]) {
        return Utilities.loadJavaScript(
    } else {
        // Class not found, just return false
        return false;
 * Keep track of files already loaded
Utilities.loadedJavaScript = { };
 * Load the specified JavaScript file, optionally
 * calling a callback function and passing a Boolean
 * as to whether the file loaded
Utilities.loadJavaScript = function(file, callback) {
    if (Utilities.loadedJavaScript[file]) {
        if (callback) {
            setTimeout(callback, 10, true);
        return true;
    } else {
        var head = document.getElementsByTagName("head")[0];
        var script = head.appendChild(
        // Set timeout of a very liberal 10 seconds
        var timeout = setTimeout(
            function() {
            function() {
                Utilities.loadedJavaScript[file] = true;
        script.type = "text/javascript";
        script.src = file;
        return true;

The script loads the additional JavaScript files by appending additional script elements to the head of the document. Before setting the src attribute of the element, it adds an event listener to clear the timeout and dispatch the load event. This ensures that any script using it to load additional files will know if and when it has loaded.

Because the loading of each additional JavaScript file returns asynchronously, late loading of resources (which can easily extend to loading images and stylesheets) needs to happen early enough to prevent the user from having to wait before proceeding. The script then can use the optional callback functionality of the class/file loader to tell whether the required resource has successfully loaded by the time it needs to use the file.

By keeping a balance between the initially loaded scripts and the scripts that are loaded as required, the application can stay light and fast to load; this practice will expand its functionality without interrupting the user.

  • + Share This
  • 🔖 Save To Your Account