Archive for the 'javascript' Category

JSUnit XML to JUnit XML

We’re using JSUnit to run tests in our build system, and we’re using Bamboo to do continuous integration.  Unfortunately, the XML spit out by JSUnit is not recognizable as JUnit XML for the purposes of integrating into Bamboo. I wrote this XSL stylesheet to transform the JSUnit XML report into a JUnit XML report that Bamboo can parse.  It’s simple and inefficient, but hey, if you are looking at this, you probably just want to get the job done (like I did). 

View jsunit_to_junit.xsl

Type enforcement and argument validation in JavaScript saves time

Debugging JavaScript is hard enough - but it is especially annoying when you have spent a good amount of time tracking down a bug and it turns out to be a type error (i.e., your function expected a Boolean true but got a String “true”). Perhaps your value was implicitly cast to another type by some operation, or maybe you forgot to pass the right arguments to a method. In a statically-typed, compiled language (such as AS3 or Java), you would find out about bad arguments during compile time - and you’d probably get a nice, descriptive error message of what was going on.  Not so with JavaScript - in fact, because it is loosely and dynamically typed, you may not find out about your bad argument until you waste an hour or two tracking down a bug.

To avoid this sort of thing, you can throw your own errors when a method or constructor doesn’t get what it expects. The pattern is easy to get the hang of.  The very first time you get one of these errors, you will feel good about all this extra typing. 

/**
* A function that creates a new barf bag.
* @param {Boolean} zip          Whether this bag has a zipper or not.
* @param {String} bagType     Valid types: "paper"|"plastic"
* @param {String} vomitType  Valid types: "chunky"|"bile"|"watery"
*/
var VomitBag = function(zip, bagType, vomitType) {
   /* validate arguments */
   if(typeof zip != "boolean") throw new Error("VomitBag: expected zip to be Boolean");
   if(typeof bagType != "string" || !(/^paper$|^plastic$/.test(bagType)) throw new Error("VomitBag: expected bagType to be String and to be either 'paper' or 'plastic'");
   if(typeof vomitType != "string" || !(/^chunky$|^bile$|^watery$/.test(vomitType)) throw new Error("VomitBag: expected vomitType to be String and to be 'chunky', 'bile', or 'watery'");

   /* some code... */
}

This technique is not at all new to JavaScript. For example, Marijn Haverbeke talks about it briefly during a good writeup about error handling in Eloquent JavaScript: Error Handling - Eloquent JavaScript (that whole site is worth reading).

Disabled form element and dispatchEvent bug in Opera

I’ve stumbled across a bug in Opera 9.27 (which I dutifully reported).  Basically, if you disable a form element and use the DOM2 dispatchEvent method on the element to simulate a click, the element fires the event.  Since the element is disabled, it should not fire any click event handlers - this is the behavior in Firefox and Safari.   Here’s the html I used to prove it:

Opera disabled form element / dispatchEvent test

Encapsulation vs. Efficiency in JavaScript

I’m an encapsulation fanatic.  I love to write code where data is protected from view and unavailable for mischief.  I like the ability to react to changes to the internal state of a function. Also, the thought of something accessing and re-writing a method or variable on another class instance scares me, and I’d rather just not let it happen.  A ton of my code ends up looking like this:

var Cookie = function() {
   var chips = {};
   this.addChip = function(type) {
      chips[type]++;
      bakeCookie();
   }
}

On the other hand, there are quite a few times when I’m writing JavaScript that I wonder when I should be worrying about efficiency.  It’s an obvious fact that using prototype methods can increase efficiency by reducing the amount of memory and processing required.  I’ve always assumed (from doing very short, non-scientific tests in a browser) that this technique pays off only when using many instances of a particular object.

var Cookie = function() {
   this.chips = {};
}
Cookie.prototype.addChip = function(type) {
   this.chips[type]++;
}

You might as well not even have the addChip method at this point. Anybody could come along and change chips - hell, they could turn it into a number or something.

Without the ability to maintain privacy, you won’t ever know when your properties change (in case you want to do something when one changes). Without privacy, you can’t hide your implementation details and provide a clean interface (in case you need to re-write the guts of your function) without a guarantee that nobody has latched onto one of the properties or methods you don’t care about anymore.

This is one of the most frustrating things about JavaScript for me. For performance, we are forced to make a decision wherein we must sacrifice privacy. Personally, I don’t use prototype methods all that much - until I know that a class I’m using will be instantiated many, many times, it just doesn’t make sense to me to lose all the benefits of privacy. Performance be damned - hell, from what I heard, you are supposed to optimize as a last resort, anyway.

I’d love to hear what other people think, though.

Use only the JavaScript that you need

I am a person who likes to use JavaScript development frameworks, such as Prototype or JQuery.  There is a time and a place for such things - as when developing your own website or working on some code that relies on lots of UI bells and whistles (fade outs, complex event handling, etc).   On the other hand, when I’m writing code that is going to end up as a distributed application, such as a widget,  I don’t think that using a development framework is appropriate.   There are a few reasons for this: 

  1. Serving only the code that is used saves user time - less downloading and less parsing.  
  2. Part of developing JavaScript applications is accepting the fact that you don’t know where your code is going to run.  You should maximize compatibility. 
  3. Frameworks make hard things easier to code - but not necessarily faster to run. 

I’ll start with the first point: serve only the code that you use.   Even when I’ve used a framework heavily on a project, it seems like there is about 60% or 70% of the framework that is useless to me.   Why should I bother with that crud?  Most of the time, it makes more sense to steal code from one framework or another to accomplish what I want to do.  More often than not, the problem I’m faced with can be stripped down to the statement: “I need a cross-browser way to do ‘x.’” If that’s all I need, I’d rather solve it myself through some simple research, or steal code from someone who has already done the research, such as PPK.   The ugly truth is that JavaScript developers need to think about bandwidth and processor overhead.   Not all users are running their browser on “decent” hardware and a fast connection.   There are no hardware requirements for JavaScript!  Sure, you need a  web browser with a JavaScript interpreter - but that includes such a large swath of browsers and versions of browsers that it’s literally a crap shoot.

Second point  - maximizing code compatibility.  I disagree with using a framework that pollutes the global scope in such a manner that it can break others’ scripts through its mere existence.  I am specifically referring to the Prototype library, which adds methods to native objects such as the Array object.   Of course, when you know where and how your code is running, use what you want.   I happen to think Prototype is a great library, and that the people working on it are incredibly smart.  On the other hand, if your code is supposed to run on a bunch of other sites, you should try to write it so that it doesn’t pollute and possibly break other scripts.   These days, there are tons of authoritative sites to find a cross-browser way to solve your particular problem. You can steal code from a framework,  Google the problem until you find a good snippet, or learn about the issue and come up with your own solution.  Using a library to solve only a few of these problems is heavy-handed if you are expecting a large amount of traffic on your particular project.  

Lastly - frameworks make hard things easy to code, but not necessarily faster to run.  For example, take the JQuery library.  It’s extremely useful to be able to query the DOM in the CSS/XPathy kind of thing that JQuery implements. On the other hand, if you are not concerned with the manner in which the library accomplishes what you ask it to do, you are asking for trouble.  The classic example is running a class name query on a large node set.  Yuck - that can take eons to complete in Internet Explorer!  Granted, it’s not JQuery’s fault that your code is inefficient - but if you had gone through the trouble of selecting all nodes and checking each class name to see if it matched what you were interested in, you’d quickly see that you were being inefficient.  When you use one of these libraries, you are tempted to use the concise, convenient syntax without caring how it works.  Understanding how it works, though, is the only way to understand how to use it efficiently.   

Next Page »