December 17, 2011
First, let’s identify the problems. Here’s a function that I just made up, but it’s not too far from the truth.
Fig 1 - A Common Site
How many differentthings are going on here? I can see four right off the bat. Individually, each is not a Bad Thing, but when they’re all within the same function, it’s a problem.
Fig 2 - Event Binding. We’re looking for something in the DOM, and then attaching an event handler to it.
Fig 3 - AJAX. Specifically, communication with our persistance layer.
Fig 4 - Business Logic. This a simplification, but we’re analyzing the data and making a logical decision based on it.
Fig 5 - DOM/UI Manipulation. We’re not just reading the DOM here, but changing it.
And this little ditty is only 11 lines long. This is the equivalent of inlining your security checks right next to SQL statements, all within a UI template. God help you if you want to actually uncovered a bug in this rat nest down the road.
And let’s not even get into testing. How would you even start writing a unit test for this function? (Hint: it sucks)
Fortunately, messy code is not a new problem. There is an embarrassment of riches out there to help you get your crap together.
A common reaction.
What makes MVC so popular amongst developers is that it forces you to break your code down into manageable chunks. Mixing AJAX calls and DOM Manipulation in the same functions just doesn’t fly there.
And, you have a bunch to choose from. In future posts, I’ll be giving a brief description of some of the popular ones. Spoiler: I myself have been using Backbone and will be going into deeper detail on that one.
Written by Scott Williams who lives and works in sunny Phoenix, AZ. Twitter is also a place.