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.

Advertisement

If You Adopt a Pattern, Stick with the Damn Pattern!

This is a bit of rant, but something that I’ve seen time and again in development groups that I’ve worked with over the years: Engineers adopting a design pattern then falling out of the pattern when it’s convenient. The most egregious is breaking out of the MVC pattern when the interaction gets difficult. Don’t get me wrong, there will always be exceptions; but especially in UI engineering, I see a lot of “falling back” on the tried and true DOM-based operations before adequately exploring whether or not it can be done within the context of the particular MVC engine that is being used.

There are several reasons for breaking from the pattern:

  • JavaScript is wide open, and there are lots of ways to skin a cat, so if you hit a bit of a roadblock, there are lots of tools available to solve the problem. But in rebuttal to that, just because you can do something, should you?
  • Because JavaScript is not strongly typed, enforcing patterns is difficult at best. Everyone has to buy into it.

What I see a lot of is falling back on DOM-based libraries such as jQuery. For instance, if you want to show a popup window to display some information from the server when a user clicks a link, the MVC way would be that the view that holds the link intercepts the click, triggers an “action” event of some sort which is intercepted by a controller that would then tell a DAO that would retrieve the information from the server. When the data is available, the DAO would fire a “data available” event that a model is listening to; the model in turn would update itself, trigger a “change” event to which a view is listening. The view updates itself, then displays the results.

This seems a little convoluted and complex but what it ensures is that you have proper separation of concerns; each different component is responsible for only what it was intended to do. The anti-pattern to this is just call a function and use jQuery or another DOM-based library to handle it all, which is totally easy. You make the call, use jQuery’s AJAX method, then display the message with a jQuery modal dialog. Simple.

But here’s the problem with that: Once you go that route, you’re using an external entity outside of your MVC system that acts completely independently of your system. That entity combines MVC and DAO operations. You could argue that that makes it a self-contained MVC. But that would be wrong because there is no separation of concerns, which is what MVC is all about. If you’re going to follow the pattern, there are no multi-roled objects.

Furthermore, the approach that is commonly taken is to make that function globally available because “Hey! It’s a cool function that we could use everywhere!,” which usually means polluting the global namespace. That has some serious security implications when you do that because you’re exposing the function to the world, and because that function is making an open server call, it is possible to expose it to CSRF attacks. Not good.

You see this behavior mostly from developers who are new to MVC. So how do you teach them? Simple. You have to get team buy-in to specific rules:

1. Obey the knowledge barrier. Look at the diagram below:

The solid lines represent direct knowledge from one entity to another. From that we can see that the controller knows about both the view and the model, and the view also has direct knowledge of the model. The dashed lines represent an implicit knowledge in that the only way for those entities to communicate with the destination object is via messages/events.

2. I mentioned this above: No multi-role objects.

3. DOM-based libraries should only be used to interact with the DOM; that is, they’re mostly used as helpers for the views. However, since they also have AJAX capabilities, they can also be consumed for use with DAO operations, but a DAO object should always be relegated to that whether the DAO is explicitly or implicitly declared. For instance, Backbone.js utilizes jQuery’s AJAX for CRUD operations. In that case, the DAO is implicit, and actually obfuscated from the developer as the models and collections interact with the Backbone.sync object which is itself a DAO.

4. Finally, to mitigate shortcuts, developers have to learn and practice good architecture and design; that is, they need to start using some sort of class and object interaction description methodology such as UML.

Those are four simple rules. Having taught this over several years, I know how difficult it can be to enforce and have developers obey them because the temptation is to always go the easy route. But great programs can only be created with a thoughtful approach to building them. Just as in construction, you wouldn’t build a house without a blueprint, and when you’re building you wouldn’t use construction methods that don’t follow the standards. Why would you do this in software?

Wednesday JavaScript Meanderings

On JavaScript Parasitic Inheritance

Hmmm…. Not sure that I really buy into all the craze in Parasitic Inheritance the last couple of years. Perhaps I’d buy into it if I heard a really great technical explanation, but thus far, all I’ve heard and read about the virtues of Parasitic Inheritance center around not having to use “this” and “new.” My reaction to that line of reasoning is “So what?” “this” and “new” are artifacts of the JavaScript language. Deal with it. Another line of reasoning used to justify the use of Parasitic Inheritance is the concept of the durable object, which is defined as “A durable object contains no visible data members, and its methods use neither this nor that. Again we return to the non-use of “this.” And again, “So what?” You can achieve something similar this using while defining a custom object in the traditional way:

function myObj() {}

myObj.prototype = (function() {
    function myPrivFunction(myArg) {
       return ...do something with myArg...
    }
    return {
        myMethod : function(param) {
            return myPrivFunction(param);
        }
    };
})();

You can have a whole set of private functions defined above the return that will not be changeable to the outside world. Furthermore, one of my biggest problems with Parasitic Inheritance is that you lose instanceof. Yes, there are ways to deal with it, but most of the examples I’ve seen deal with overriding Object and Function prototypes, or creating some intermediary “helper” function to enable instanceof with Parasitic Inheritance. My thought about this is if you have to make changes to the core of the language, then the “solution” you’re providing is simply an interesting engineering exercise.

On MVC: Put the DOM in Its Place, Dammit!

One of the things I see quite a bit of when working with JavaScript developers who are relatively new to using MVC frameworks such as Backbone.js is that their thinking is very DOM-focused. And while MVC in JavaScript does mean interaction with the DOM through the View, most developers focus their thinking around the View. As a result, their programming is all about direct references. But MVC is about separation of concerns, and each part of the MVC has an important role to play. As such, one of things that I do my best to help “teach” is having developers divorce themselves from DOM-based thinking, and start thinking at a much higher level; specifically, the system or application; breaking the application or system into constituent MVC parts.

Admittedly, it’s difficult for many to make the conceptual leap into MVC thinking because what we as UI Engineers produce ultimately shows up on the DOM. But the DOM is a by-product of MVC interaction. Once you get that concept down, then thinking with a perspective of MVC becomes quite easy.

It doesn’t help matters much when you have examples that are very DOM-focused, as many developers that move over to MVC are expert in jQuery or YUI or prototype.js, what have you. As a result, these developers provide examples that lean heavily on that previous experience. It’s a bit of vicious cycle.

Thoughts On My Interview Process and HTML 5 / CSS 3

I’ve been interviewing for the past couple of months, and the bulk of my interviews have been with new companies. Many have some very interesting stories, and almost to the company, each one is really focused on the latest versions of HTML and CSS. Admittedly, my actual work on HTML 5 and CSS 3 has been minimal at best, though I am taking the time while I am not working to “woodshed” and get familiarized with the concepts and do some exercises in HTML 5 and CSS 3 so my ramp-up time once I get a job will be minimal.

Now one thing that I’ve observed when I look back on all the interviews I’ve had when the subject turns to HTML 5 and CSS 3 is a focus on the new, “sexy” elements, such as video, but moreover, the focus is on CSS 3. To me, when the focus is purely on the CSS 3 side of it, it’s only really telling half of the story.

I understand, people want “sexy.” But I’ve learned over the years that the ultimate presentation is secondary to the structure of the document you’re presenting, for the simple reason that without a good document structure, you’re asking for trouble down the road when you want to change things up in your presentation. If you’ve written a document structure that’s tailored to a particular presentation, you run the risk of it only being able to be used with that presentation and that presentation alone. This is precisely why it was encouraged NOT to use tables for layouts because tables literally fixed you into a grid structure that could not easily be modified at a later date.

With HTML 5, the game has completely changed. Though it is not fully complete nor ubiquitously available in all browsers, we UI developers finally have a set of tags that allow us to precisely describe a document. To me, that’s the crux of HTML 5. It’s not the new features and things you can do with CSS 3; it’s the document. Repeat: It’s the document.

For years, I’ve been seemingly howling at the moon with both designers and other engineers about the importance of document structure. I communicate well enough where we ultimately come to an agreement, but it is trying sometimes.

A little sidebar…

During the course of writing this article, I remembered one of my on-site interviews; one in which I failed miserably on the HTML part. But I learned my lesson in that one and actually came up with an even better solution than what the interviewer presented to me. The challenge was to create a horizontal “stoplight” of three squares, colored red yellow and green and do it with as little HTML as possible.

I immediately used divs and anchors, which was clear that that was not a minimal solution. The right thing to have used was an unordered list, then use :first-child and :last-child pseudo selectors to style the end pieces. The CSS solution that the interviewer came up with employed floating the li’s left to get them horizontal. That’s totally valid, but based upon my woodshedding with CSS 3, I came up with a different solution that instead employs display:table-cell to get the li’s to line up horizontally. Here’s the HTML:

<ul id="priorityList">
    <li> </li>
    <li> </li>
    <li> </li>
</ul>

And here’s the CSS:

#priorityList {
    list-style-type:none;
}

#priorityList li {
    display:table-cell;
    width:30px;
    background-color:yellow;
    cursor:pointer;
}

#priorityList li:first-child {
    background-color:red;
}

#priorityList li:last-child {
    background-color:green;
}

#priorityList li:hover {
    background-color: #EFEFEF;
}

After I started getting myself familiarized with CSS 3, returning to that interview example, I could’ve scored some pretty big points with this solution. 🙂 It’s actually significantly less CSS than what the interviewer came up with, and satisfies his basic requirements. Note that there is a non-breaking space in the li’s, but it’s not showing here in the article for some reason. I think WordPress is reading it, as opposed to obeying the “pre.” Oh well.