22 Feb 2012

Writing applications versus frameworks

At work, since I mostly write web applications I usually end up consuming frameworks rather than writing them. So, I have been reading a lot of framework-ish code on GitHub lately, and it has turned out to be an awesome source for finding clever tricks, patterns and coding conventions.

Writing frameworks requires a slightly different mindset to programming. While writing application code, readability and maintainability are the top things on my mind, and rightly so. However, when writing frameworks, while code cleanliness is still important, they sometimes have to take a backseat when compared to performance and the ease with which the framework is to be consumed.

Consider the following two versions of memoization functions (snippets from Oliver Steele):

// version 1
Bezier.prototype.getLength = function() {
  if ('_length' in this) return this._length;
 
  var length = ... // expensive computation
  this._length = length;
  return length;
}
 
// version 2
Bezier.prototype.getLength = function() {
  var length = ... // expensive computation
  this.getLength = function(){return length};
  return length;
}

The second version (which uses the Russian Doll pattern), is better optimized but makes the code harder to understand and debug. I have found this to be true when using other metaprogramming constructs (method_missing anyone?) as well. There is always a struggle between writing readable idiomatic code and clever hacks that makes a library faster and cute for the consumers.

The same could be said about writing truly REST-ful services. Ultimately, it should be pragmatism, and not dogmatism that should govern our decisions.

Tagged with:

Leave a Reply