On Classical Inheritance in JavaScript

Whenever I get involved in conversations revolving around classical inheritance in JavaScript, I usually have a couple of comments:

  1. Geez! Man up and learn the f-in’ language!
  2. JavaScript is a class-less language, why would you want to do classical inheritance?!

Comment 2 is usually followed by a variant of Comment 1.

Earlier this year, I wrote a short quip on not buying into Parasitic Inheritance trend. Prior to landing my current gig, I had interviewed with several companies that were employing it in their applications. The things they were doing were very cool, but the reason almost all stated for using it was that they didn’t have to use “new.” I brought up the issue that in order to create a descendant, you had to make an entire copy of the ancestor, then tack on the new methods; whereas natively, it was a simple graft of new methods onto the ancestor. It fell on deaf ears as they justified what they were doing by citing Crockford’s work on classical inheritance in JavaScript.

But I don’t think they read the very end of the article in which he states – in a bordered box no less – that his attempts to support classical inheritance in JavaScript was a mistake. Here’s the text:

I have been writing JavaScript for 8 years now, and I have never once found need to use an uber function. The super idea is fairly important in the classical pattern, but it appears to be unnecessary in the prototypal and functional patterns. I now see my early attempts to support the classical model in JavaScript as a mistake.

The challenge with JavaScript is that it is a wide open language; you can do just about anything with it. But just because you can do something doesn’t mean that you should…

Yeah, I’ve heard all the complaints over the years – coming especially from former Java programmers. But I just keep on going back to the two comments I made above, especially the first comment. My belief is that if you’re programming in a particular language, learn the f-in’ language. Don’t try to place a different model or pattern on the language just because you’re used to programming in another language. To me, doing that is the ultimate in bullshit hubris. JavaScript is a powerful language, though admittedly it does have its shortcomings, but if you take the time to learn the mechanics of the language, there’s not much you can’t do with it.

Advertisement

If MVC Is So Simple, Why Does It Get Screwed Up So Much?

Seems to me that there are lots of developers out there who have taken up the MVC banner, and charged forth into battle; silently crying out, “MVC! MVC! All apps should be MVC!” Or maybe it’s just me that did that… 🙂 Regardless, over the last few years, lots of people have adopted the MVC design pattern as their pattern of choice. But from what code I’ve seen, especially in the JavaScript world, most of it plain shit as far as following the pattern is concerned.

The most egregious guffaws are confusing object roles in an MVC system. I don’t know how many times I’ve seen objects that cross the Controller-Model or Model-View or View-Controller boundaries; intermingling roles within a single object. Other things I’ve seen are people defining objects to fill a particular role, then do all communication via two-way direct reference between objects. Or worse yet, I recently saw some code where the developer was having a controller make his view trigger an event to which the same view was the only listener! Yikes!

One could just call it stupidity on the part of the developers, but I’ll be more forgiving and say that all that boils down to simple ignorance of how the objects – and more importantly, how objects communicate in any MVC system – should work; or just plain ignorance of what MVC is all about.

The Model-View-Controller paradigm at its most pure is quite simple: It’s all about separation of concerns, and consigning “concerns” to three, specific classes of objects – Model, View and Controller objects. Each class has a specific purpose and role. In this installment, I’m going to talk about each of these classes, and how they should be used to build successful MVC applications.

Model

A Model is an application’s representation of the underlying data set; in other words, it’s data. It has accessor methods in the form of getters and setters to manipulate the data. It does not or should not contain business logic. Unfortunately, some 3rd-party libraries such as Backbone.js muddy the waters a bit by adding things like the “validate” method to allow data validation within the context of the model. I’ve always found this to be just plain wrong. While you certainly can put logic in the model by virtue of JavaScript not having any barriers to doing so, muddying the waters in the model’s role in this respect I believe does more harm than good.

To me validation is really the job of the controller, which should be the one that “owns” the business logic. However, I’m also in favor of placing validation logic in the view to encapsulate it and remove some of the burden from the controller, since validation is really view-specific.

A model’s role is simply to store runtime data. Consumers of the model can get or set attributes on the model. But when that data changes, the model is only responsible to notify listeners that it has changed. To me, that’s it.

View

To me, there are two types of Views: Smart Views and Dumb Views. Smart Views have a bit of logic in them, namely input and output validation logic to make them “smart” per se, but as the endpoint objects – that is, the objects that clients actually “see” – they should never contain core business logic. Actually Smart Views are simply Dumb Views with some validation. Some have argued that a Smart View could also be one that includes Model functionality, but I don’t subscribe to that at all. I think object roles should be distinct, and Views are responsible for presentation of data contained in their associated model. Period. As for “Dumb” views. They simply exist to display model data (and update the model if they’re used for input), and update themselves when the model changes. Pretty straight-forward.

But with any view, I found that following the following rule-of-thumb has saved me countless hours of anguish, and that is simply: A View knows about its DOM and its DOM only. It knows about no other View’s DOM. This is extremely important to consider, especially if you’re using Backbone.js whose views are normally attached to existing HTML elements, and not blitting out their own HTML. When you create a Backbone view and assign its “el,” you have to make sure that no other view – as you can potentially have several views on a page – can manipulate DOM represented by that “el.”

Admittedly, when I was new to Backbone, coming from a system I helped create whose views all contained their own HTML, I broke this rule because hey! jQuery lets you get the reference to any HTML element so long as it’s in the DOM tree. But I ran into a bit of trouble when I had multiple views on a page accessing the same region of the page and using the same el. It was a nightmare to try to maintain. I no longer do that, as I’ve learned that lesson, but mark my words: Your view should only be responsible for a distinct “el.”

Controller

Especially in JavaScript, a Controller is almost superfluous, as it is mostly used as an instantiation device for models and views. But it can carry “safe” business logic; that is, business logic specific to the operation of the application that doesn’t expose trade secrets. It is also used to control application flow. Circling back to Backbone.js, in earlier versions of Backbone, the “router” object was called controller, but was later renamed to router. I think this was a smart move because a router is simply a history manager wrapper. It doesn’t control application flow. That’s the controller’s job.

For instance, I’m currently building an application  where I have a master controller that instantiates several sub-controllers representing sub-modules of the application. Based upon user input (a click of a button or a link on a page), the controller decides that module to instantiate and display. It then tells the router to update the route to reflect the “destination” in the browser’s URL. In this respect, I’m using the router simply as a view, as all it does is update the URL, or on the reverse, tells the controller to display the right module or section depending upon what was entered in the URL.

In other words, a controller is responsible for controlling application flow. That’s all it does. It can listen and respond to events in the model and views. It can even trigger events to other controllers. But in no way should it contain data manipulation or view functionality. Leave that to the models and views of the system.

Look, MVC is not rocket science. But it may feel as if it is especially if you’re doing it wrong. And believe me, lots of people are doing it wrong.

Want Your Team to Write Maintainable JavaScript? Start Making Them Think Alike…

A colleague at work today posted a couple of JavaScript/Front-End Development conferences that are coming up in the near future. One of them, the O’Reilly conference has a speaker talking about writing maintainable JavaScript. I did a bit of searching on him speaking about this topic, and the material that he presents is generally pretty good – at least from a coding standpoint. But I think that focusing only on coding won’t solve the problem. From personal experience, nothing can mess up maintainable code more than bad or non-existent design practices.

I know I don’t get too much traffic to this blog, but for those who have read my technology articles, they’ll know that I have a real design focus. Why? Simply because high-quality, easily maintainable software starts with good design, and I have LOTS of personal experience in this. I was able to get roughly 200 front-end engineers at a previous company to code the same way – in a maintainable fashion – by first teaching them good design practices. It all started out with using UML as the way to communicate our designs, then writing good technical design documents to describe and discuss the diagrams, then writing code that followed the designs. Of course, included in the process were both design and code reviews ensuring that the final product that was produced with lots of input and feedback.

Most would think that adding all this onto the development process would tack on more time to development. Admittedly, at first it does. That’s the “learning tax.” But once people are used to doing designs, and going through a few review processes to defend their designs and code, they become faster at development; much faster than they were before they started practicing “design first, code later.” While this also requires an overall organizational acceptance, it’s an easy sell because the overall code quality will shoot through the roof.

Plus, doing design then coding is the fundamental difference between software engineers and code monkeys. I’ve been around long enough in this industry to say that most software developers, though they like to think of themselves as engineers are code monkeys; albeit, with varying levels of experience. The more experienced developers will most likely be able to tackle a problem and get it right a lot of the time, but to me, when there’s not a design to accompany the development, there’s always a risk that problems that could’ve been mitigated and avoided with a design will trickle through. That’s not to say that a design will mitigate all bugs. That’s ridiculous. But you can avoid lots of problems simply by doing a design and following it; that is, implementing code according to what’s described in the design.

To crystallize the point further, let me say this: Code is PRODUCT; design is engineering. And when people are designing in the same way, they will tend to adopt coding practices and standards that are similar and maintainable throughout the organization.

So which do you want to be, engineer or code monkey? If you’re not already doing design, you know who you are…

A Real Pet-Peeve

Now that I’ve pontificated on the virtues of design, I’ll discuss code. The speaker on writing maintainable JavaScript, Nicholas Zakas, is quite an engineer, currently a principal at Yahoo. But in reading through his blog and reading through the conference highlights, plus reading this article that he wrote on the subject, he missed a VERY important point that is one of the very things that pisses me of more than anything else and that is lack of comments. I’m very good about commenting my code simply because once I’ve got it checked in, I want to be able to get a gist of the flow when I return to it weeks, months, or years from when I wrote it. I also do it so that others who may maintain my code after I’ve left know what I’m doing in my code.

I’ll just say it plainly: Commenting code is Programming I; not 101. You should be commenting your code from the get-go. Period. It’s such a key component to team coding and writing maintainable code, but it is often missed in talks and lectures because it’s assumed people do it. Nick, believe me, they don’t. 🙂

A Particular Caveat About Backbone.js Development

I’ve been developing an MVC application using Backbone.js as my MVC engine. This is a very powerful framework and its capabilities extend beyond a proprietary MVC engine that I helped develop in a previous company. One thing that I absolutely love about Backbone.js is how you can use a third party DOM library such as jQuery. With the proprietary MVC engine I helped develop, we actually stringified our HTML and wrote it all out with innerHTML, and DOM operations were performed with DOM scripting. You might think this is screwy, but it ensured that we followed a fundamental rule: No component could know about another component’s DOM. The net result is that all view objects were completely encapsulated and their DOM’s protected from other objects.

With jQuery and other DOM-scripting libraries, all you need is a selector, and that sort of opens up your views’ DOM’s to be open to manipulation. I even found myself starting to do this in a module that I built where a two-column informational table was actually constructed from four different data sources and four different views. Luckily, I fell back on my old experience and made the conscious decision that my individual views would only know about the specific section of HTML for which they were responsible. But I could’ve easily broken the rule that a component only knows about its DOM and its DOM only.

You might ask, “So what? What’s the harm in that?” There’s actually not much harm of that, but if you have two components competing for the same patch of HTML, you could have some deleterious results. So my advice here is relegate your views to specific sections of HTML on they and only they act upon. This will ensure that you won’t stepping all over yourself and having to deal with resource contention.