Scriptaculous and Why 'extends' is Evil

The extends keyword is evil—maybe not at the Charles-Manson/Vlad-the-Impaler level, but bad enough that reputable designers don't want to be seen in public with it. The Gang-of-Four Design Patterns book is, in fact, largely about replacing implementation inheritance (extends) with interface inheritance (implements).

-- Allen Holub, Holub on Patterns: Learning Design Patterns by Looking at Code

Holub can be a bit controversial in OO circles. He throws bombs like "getters and setters considered harmful." Not everyone likes or respects him, but beneath some of that hyperbolic language, he makes some good points. Some of the arguments he makes about OO in general, and Java in particular, can easily be applied to the world of JavaScript and Ajax libraries.

Take Scriptaculous and Prototype, for example. Because JavaScript is missing some of the syntactic sugar for traditional declarative OO programming, many utility libraries take as their first task the creation of functions that make creating class hierarchies much easier. With this tool in hand, like a novice Java or C++ programmer on a bender, everything is inheritance. Everything.

Now I like using Scriptaculous, but Object.extends makes far too many appearances in it for my taste. Pretty much every effect is implemented by extending Effect.Base. The only exception is Effect.Parallel, which allows you to compose two simple effects. The resulting code is somewhat messy and difficult to modify, since the design mixes two different concerns in a single object: the scheduling of the effect and the actual DOM modification that achieves the effect.

Having started the porting of Scriptaculous to GWT (GWTaculous), I was very tempted to replace inheritance with something like the Command pattern, essentially composing the scheduling part of the effect with the DOM modification part, as mentioned above.

Right now, changing Effect.Base is extremely difficult, as doing so would break all of the effects subclasses (the Fragile-Base-Class problem, as Holub calls it). A clearly defined command interface would simplify that immensely.

There is good news on the horizon, however. Some JavaScript/Ajax libraries are starting to show a little more OO sophistication. Take Ext JS. In Ext JS, the behavior of widgets and components can be modified through the composition of different objects. To have a data grid widget, for example, retrieve it's data from a file, a static JSON structure or an Ajax call, all that is necessary is to pass an appropriate object to the widget that implements a well-defined interface. No extends necessary. Nice.

So, when writing frameworks or even a large application or library in JavaScript, view extends with mistrust. Most times, there is a better (in OO terms) way.

Technorati Tags: , , ,