Object Oriented JavaScript Techniques 4

This post is in response to a couple of conversations I had with some friends around OOP in JavaScript. Over the last couple of months I have gotten really deep into the language with JQuery (which is a fantastic library by the way) so I thought I’d quickly list some techniques I have been using to structure my JavaScript code.

Creating a very simple class with an instance variable:
JavaScript has no concept of classes but they can be mimic-ed by creative uses of the Function object. So for example this is completely valid:

var vanillaFunction = function(){
	this.name = "vanilla"
}
var instance = new vanillaFunction();
alert(instance.name) //	vanilla


In the above case, “name” becomes an instance variable of the vanillaFunction class.

Constructing instance methods

var vanillaFunction = function(){
	this.name = "vanilla";
	this.sampleMethod = function(){
		return "SampleMethod was called";
	}
}

var instance = new vanillaFunction();
alert(instance.sampleMethod())

Under the hood whats going on is that the JavaScript interpreter is attaching the Function objects to the vanillaFunction’s prototype chain. So to add another function, we can append that function right on the prototype:

vanillaFunction.prototype.getName() = function(){
	return this.name; // returns "vanilla"
}

Note that these functions have access to the name instance variable defined in the main vanillaFunction class.

Creating class variables and methods (kinda):
Since all functions are essentially Objects, variables can be tagged on to the function object and then referenced as static class variables.


vanillaFunction.classVar = "some value here";

Same way, static functions can be created as well:

vanillaFunction.staticFunction = function(){
	alert("static function called");
}

However it should be noted that the static variables and methods do not have access to each other unless explicitly passed during invocation. Personally, I hardly ever use this and prefer static classes as shown below.

Creating Static classes:
A static class is one you can never create a new instance of. For example, instead of having static methods in a JavaScript class, you can create a static class by declaring your functions as variables on a pure JavaScript Object. This method can be used for example for creating a class of utility functions:

var utils = {
	trim:function(str, numCharacters){
		return str.substring(0, numCharacters);
	},

	log:function(msg){
		if(console){
			console.log(msg);
		}
	}
}
var s = utils.trim("Good day to you sir", 4);

Creating classes with JQuery
To create a class with JQuery, we use the jQuery.extend function which pretty much adds the instance methods to the prototype chain as we saw before:


MyClass = function(){
this.title = "MyClass";
};

$j.extend(MyClass.prototype, {
toString:function(){
return this.title;
}
});

Events:
Even though the ECMAScript specification defines events and how they work, they are not implemented consistently across browsers. The JQuery event system is much nicer since a) it works cross-browser and b) the event source doesn’t necessarily have to be a DOM element.


var obj = {name:"SimpleObj"};
jQuery(obj).bind("objectChanged", listener);
jQuery(obj).bind("objectChanged", listener);
jQuery(obj).trigger({type:"objectChanged"});

In the above example, we are binding to a custom event of type objectChanged. Usually, I access the event type as a static class variable:


var CustomEvents = {
OBJECT_CHANGED:"objectChanged";
}
jQuery(obj).bind(CustomEvents.OBJECT_CHANGED, listener);

That covers pretty much the basics oF OOP in JavaScript. A lot of metaphors (like private/protected/public accessors) may be missing here but I havent really found that to be too much of a problem. These metaphors have made my code a lot more manageable.

Further reading:
John Resig’s list of lessons in advanced JavaScript

Video worth sharing: Life Inc The Movie, A nine-minute history of corporatism. 1

Life Inc. The Movie from Douglas Rushkoff on Vimeo.

Another book on my to-read list

Personal landmark moment: My first patent: On the design of Comcast’s Fan Player 4

I joined Comcast four years ago, fresh out of graduate school with a Masters in Computer Engineering and a passion for the Flash programming language. Back then, Comcast was one of the rare companies that had invested heavily in Flash and getting the opportunity to develop applications in Flash that would be seen by a huge number of users was an exciting opportunity.

One of the first apps I got involved in and was my main project till about a year ago was the Fan. Originally concepted by my then boss and later friend and mentor named Jeremy Landis, the Fan was a unique application. Comcast was probably one of the first companies who invested in Flash video back when it had just about come out. When I joined, the Fan version 1, was written with all the goodness of Flash 6: code in frames, gotoAndPlays, etc etc. That was not too easy to work with and the app was ported to the goodness of ActionScript2 soon after the release of Flash Player 7. Version 3 of the application added some amazing redesign by our new design lead, Alfredo Silva and some amazing interaction models by Gabo (of Gabocorp fame). The 3.5 version of the player introduced the ability to switch to a more conventional square view. There was a sentiment that adding a more conventional interface would lower the barrier to users actually interacting with the application more. The square view was extended even further in Fan 4 which was also written from ground up in Flex 2. Porting the circular view to Flex 2 was an interesting challenge and I think we did an amazing job with Flex custom components.

The circular view was discontinued early this year as was the monolithic Fan application with the Comcast.net portal moving to a more conventional single-video-on-page experience.

Its kind of ironic that today the original team responsible for the Fan was awarded the patent by the United States Patent office on the design of the application. My first patent! How f-ing awesome is that !!!

The Fan was always unique if anything, and there was always the debate whether a circular interface was indeed the best to watch rectangular video. But the people loved it for sure, so much so that it even won the Flash Forward People’s Choice award in Sept 2006, and yes, that was for the circular interface. I remember a lot of stories from friends who had parents/relatives who loved the circular interface, and it was perplexing to the usability folk, after all it was clearly breaking all rules of application design. But that was where the magic was. It was different, iconic and had a long history with the Comcast customers who used it to catch up on daily news, events, gossip, etc. Heck, it was cool! Cool enough for even Philebrity to run a post titled The Only Thing Comcast Ever Contributed To The Internet: “The Fan” (Philebrity posts are not usually the most Comcast friendly).

But anyway, this is a moment to celebrate. I have one more fond memory of the Fan now, and believe me, this one is hard to forget :) . Special thanks to all who went towards making the Fan a successful product, the editors, content video team, the design,dev and QA teams, etc. This was a fun ride.

Fan 1, 2

Fan 3

Fan 4

When things go wrong: Communicating error and gathering information for client side code 0

Having developed client side applications for the last few years in a variety of languages (Java, Flash, AIR, Javascript and recent forays into Objective C for the IPhone), its funny that some discussions appear cyclically and are discussed as though for the first time in every new project. Communicating errors in your application seems to be one of them, and I wanted to pen a few thoughts on that.

Serverside developers have it easy!
Well, no ;) . But there are paradigms that have become the norm now. If something bad happens and you get a 404 or a 500 error on a webpage, its pretty likely that its been logged and if its on a major product, alarms have been raised. Client side code, especially in the languages I have worked in the last couple of years, have been less…communicative. I would like to focus on AIR and Flash here since those are the technologies I work with most often. The problem becomes more critical in AIR where you have much more things that can go wrong since you are interacting with items on the user’s machine which is not a controlled environment.

Why communicate the error?
Very few client side web apps I have worked with, including my own, have ever seemed to have handled error correctly. Most of the time, the app has been scoped with time allocated against the features and error states have never been considered. Occasionally, a developer will put in an Alert window or something similar just as a precaution (I know I have). In Flash/AIR there doesnt seem to be a good library that I can integrate into my application that encapsulates best practicess. Heck, I dont even know what the best practices are, which is what prompted me to write this post.

What would you include in the error window?
While you may want to include app specific information in the error window, I think there are a few things that make most sense:

  • An error description: What happened ? Corrupt file? Cannot connect to server? Something readable. For bonus points, can the user do anything about this, like restart the application?
  • An error code: This makes sense and if you include a support system, like a bug tracker or a 1-800 number, it would make the conversation a lot more meaningful
  • The detailed stack trace: A good paradigm I have seen here is a toggleable details state that shows/hides the detailed error stack trace, would go a long way in figuring out the source of the error
  • Extra points: email API integration, or some other way for the user to send the error description with as little pain as possible

The last point is kind of interesting, cause you might want to send more than just the stack trace of the error. You might want to set the whole application state. If you have application logging enabled, say with something like the CIM logging framework, the whole log file might be of interest. Again, the developer must ensure that he is only logging non-personal information there.

Of course there are situations when the error might cause the entire app to blow up, without giving it enough time to react to the error. Would it make sense to log and end of session event and allow users to send the application log to the server if the end of session was not successfully logged for a prior session?

Prior Art:

I started looking at some Google results for Error dialogs and crash reporters. Here are some screenshots:

First is the JXErrorPane, a Java class part of SwingX project. This seems to be the most familiar UI for reporting errors(link to API docs)

jxerrorpane

The usage is pretty simple:

try {
//do stuff.... something throws an exception in here
} catch (Exception e) {
JXErrorPane.showDialog(e);
}

A step up would be the UI from crash reporters which would perhaps be overkill for a web app, but would make a lot of sense for desktop apps, especially in the beta stages. Here is a screenshot from something called Bug Buddy.

Bug Buddy

Whats kind of interesting here is that it adds a field that allows user to add information about the context of the crash, as well as an email address that may be used to contact him or something.

The last screenshot is from an open source library called JRFeedbackProvider someone presented at the Philadelphia Cocoa Users Group.

JRFeedbackProvider. This has the features of the previous crash reporters but also adds a “request a feature” tab which is great if you are running an alpha version of your application and are looking for more than bug reports.

If you have seen any other error UI that seem to do a good job, please add a comment here.