Saturday, February 25, 2012

JavaScript Coding Style

I've been working with jQuery quite a bit lately, and of course doing anything really unique in jQuery can lead to taking a look at a number of jQuery plug-ins. I came across one, that I find both very useful and extremely frustrating all at the same time.

The plug-in is small and seems both efficient and effective. It does what it was meant to do and seems to do it well. My problem with the plug-in is that I wanted to make it do something new, something very much like it's intended feature, but with a new requirement.

Unfortunately, I found the code difficult to work with, here is a sample:

function memento(t, th) {
 var w,
 m = 0,
 i = 0,
 aux = [];
 if (th) {[removeAttr](width);
  if (t.opt.flush) {
   S[] = "";
  w = S[].split(";");
  for (; i < t.ln; i++) {
   aux[push](100 * w[i] / w[t.ln] + "%");
   th.eq(i).css(width, aux[i]);
  for (i = 0; i < t.ln; i++), aux[i]);
 } else {
  S[] = "";
  for (i in t.c) {
   w = t.c[i][width]();
   S[] += w + ";";
   m += w;
  S[] += m;

In the interest of full disclosure; there were comments, but I've left them off because I wanted to focus on the coding style not the comments. In fact, leaving them off in some cases made the code easier to read (and clearer where the code seemed to differ from the comments.) In general though, without the comments and the context, I don't think you have a chance of knowing what's happening in this method, and that is what I think is wrong with it.

The 'S' in the code is sessionStorage, the 't' is a table, the 'th' I believe to be a <th> element, so that one really is descriptive, but you cannot tell from the context because the other variables are reduced to single character variables.

I suspect that the original author did this to minimize the code, but in doing so I feel they have created code that is unnecessarily difficult to work with, and I don't get why. Why make all the variables single characters if you're going to leave in all the whitespace? Why hand minify when there's several readily available tools to do it for you? It did more to obfuscate the code than it did compact it, and not knowing the original authors intent, I have no idea why they did it this way.

Anyway, this was from an open-source plug-in that I had been considering using. It's almost perfect for my needs, but the style makes it something I wouldn't ask others to maintain and so, I think I'm going to have to rewrite it from scratch.


So, now I'm curious what others think, have I gone off the deep end? Am I being pedantic? Is this code something you would happily use in a project?

No comments:

Post a Comment