July 16th, 2007

run the fuck away

JavaScript Design Patterns (Gang of Remy)

Javascript Design Patterns

I'm a huge fan of Design Patterns. For those that might not be familiar with Patterns, the summary is this: Design Patterns are reusable fragments of application designs that can be used to solve a variety of problems. Pre-designed solutions that you can plug into your own application, and thus minimize development time and reduce program complexity. If you do any programming and don't know these learn them!

Now, the GoF patterns were designed around traditional OOP languages. In their book, they used C++ and Smalltalk- the latter being one of the original OOP languages, the former one of the most well respected and recognized. Patterns became extremely popular in response to Java development- another traditional OOP languages.

JavaScript is not a traditional language. In fact, it has some pretty important things that make it different.
Collapse )
These are a few Design Patterns adapted and developed for JavaScript. The important thing to keep in mind is not the details of individual patterns, but the goal of good software design. Patterns are a tool for designing good software, but they do not guarantee that your software well be well designed. They are easily misapplied, misunderstood and misused. Your end goal is to develop easy to maintain and usable applications. Apply patterns insofar as they help you reach that goal, but don't get enslaved to them.

I highly reccomend the MixIn pattern for JavaScript. It's a very powerful way for adding functionality to classes. Used in conjunction with the Decorator pattern, it allows features to be added without modifying the underlying classes- which is a great way to adapt complex code libraries to the specific task at hand. For many JavaScript tasks, however, that sort of flexibility might be more than is really required. JavaScript's functions-as-variables concept allows for lightweight implementations of things like the Strategy pattern, and are worth considering. I all but guarantee that you'll be using the MVC pattern in your JavaScript applications, even if you don't formally discuss it.

EDIT: Upon further testing, the AutoDecorator doesn't nest properly. That is to say, an AutoDecorator should be able to decorate another AutoDecorator. It doesn't, currently. I'll have to poke around in the code some more. This sort of problem is harder than normal to diagnose, because of the use of "eval"- which proves my point- you shouldn't use them.

EDIT AGAIN: I now have a working version of the AutoDecorator. It involves the use of closures, which are complex enough to require their own essay. I'll come back to that later. Closures are actually very important when one starts attempting to do code generation in JavaScript- I'll discuss them in a later essay to give a picture of the details.