Monday, April 08, 2013

Angry Birds of JavaScript: Green Bird - Mocking

Introduction


A diabolical herd of pigs stole all of the front-end architecture from an innocent flock of birds and now they want it back!

A team of special agent hero birds will attack those despicable pigs until they recover what is rightfully theirs, front-end JavaScript architecture!

Will the birds be successful in the end? Will they defeat their bacon flavored foe? Let's find out together in another nail biting episode of Angry Birds of JavaScript!

Check out the series introduction post for a list of all the birds and their attack powers.

Previous Attacks


Green Bird Attacks


In this post we will take a look at the Green Bird that can penetrate all of those hard to reach places and will mock and spy those stealing swine right where it hurts!. Slowly, one by one, the birds will take back what it theirs to keep!

What Was Stolen by the Pigs?


For the most part the birds are all front-end web developers only and don't focus on the back-end much at all. As a result the birds have a symbiotic relationship with the Water Buffalo. The Buffalo write the back-end of the application and the birds develop the front-end. The problem with this arrangement is that while the back-end is being developed the birds are left twiddling their feathers until the Buffalo are finished. However, once the back-end is done the pressure is on the birds to deliver while the Buffalo sit idle by the watering hole in the shade. Thankfully, a while back, a Green Bird proposed the idea of mocking the back-end services so they could make progress on the front-end while they waited for the Buffalo to finish their work! The Green Bird introduced a couple of handy libraries to make mocking a much easier process.

However, during a recent invasion the pigs stole the birds' mocking libraries! As a result, one of the Green Birds has been tasked to reclaim what has been stolen. He will use his overwhelming power of trickery to help destroy the pigs in order to take back what is theirs.

The Twitter Application


We are going to take a look at a simple Twitter application that gets the tweets from a specific username. Why Twitter? Well, the Angry Birds have a special relationship with Twitter, especially the Blue Bird ;)

The following application grabs data from Twitter using JSONP. I thought about using Backbone.js to write the little application, but thought that might be overkill to introduce the mocking concept. You will also notice I am not using a templating engine and that is on purpose. Another Angry Bird will be introducing that concept ;)


The above code snippet is running in the below embedded jsFiddle. Feel free to run the code and launch the editor to play around with it.

Twitter Application using api.twitter.com




The data that comes back from Twitter looks something like the following screenshot...


Mocking Static Data


What if Twitter goes down, is unstable, or you just want to test your application without having internet access? This is where being able to mock the back-end service can be really helpful. Thankfully we can use a jQuery library called Mockjax. All you need to do is call $.mockjax and provide a URL that you want to listen for and a response that you want to be returned. The following is an example of mocking the call to api.twitter.com and passing back some static data.


Not only is this pretty cool and can be helpful for developing the front-end independent from the back-end, but it also very handy when writing Unit Tests that use Ajax.

The above code snippet is running in the below embedded jsFiddle. Feel free to run the code and launch the editor to play around with it.

Twitter Application using Mockjax




The data that comes back from Mockjax looks something like the following screenshot...


Mocking Dynamic Semi-Random Data


One of the downsides of this technique is that generally I am pretty unimaginative and lazy when making static data examples. I typically end up have the same object and just increment some of the values by 1 or something. That is fine and all, but it is a nuisance, it takes time, and it doesn't really give you an idea of what the UI could look like. Thankfully there is another nice library for that called mockJSON. You provide a template of what you want your data to look like and then you give it some metadata about what types of fields you want, how many, etc... The following is how I rewrote the previous example, but will randomly generate anywhere from 5 to 10 twitter objects to be displayed.



The above code snippet is running in the below embedded jsFiddle. Feel free to run the code and launch the editor to play around with it.

Twitter Application using Mockjax & mockJSON




The data that comes back from Mockjax with mockJSON looks something like the following screenshot...


Attack!


The following is a simple Angry Birds clone using boxbox, a framework for the box2dweb JavaScript physics library, written by Bocoup's Greg Smith.

Press the space bar to launch the Green Bird and you can also use the arrow keys.


Conclusion


It can be difficult to develop both the front-end and back-end independently. Thankfully there are some techniques and libraries today that can enable the front-end to develop and prototype separate from the back-end progress. The mocking techniqiue with static data can also be helpful when Unit Testing your code as well.

There are many other front-end architecture techniques that have been stolen by the pigs. Tune in next time as the next Angry Bird takes its revenge! Dun, dun, daaaaaaa!

Thursday, April 04, 2013

Angry Birds of JavaScript: White Bird - Linting

Introduction


A diabolical herd of pigs stole all of the front-end architecture from an innocent flock of birds and now they want it back!

A team of special agent hero birds will attack those despicable pigs until they recover what is rightfully theirs, front-end JavaScript architecture!

Will the birds be successful in the end? Will they defeat their bacon flavored foe? Let's find out together in another nail biting episode of Angry Birds of JavaScript!

Check out the series introduction post for a list of all the birds and their attack powers.

Previous Attacks


White Bird Attacks


In this post we will take a look at the White Bird who appears to be seemingly harmless, but when it pulls out it's strict coding style and bursts of quality checks the hogs are sure to squeal. Slowly, one by one, the birds will take back what it theirs to keep!

What Was Stolen by the Pigs?


The birds all learned how to program in a slightly different way. Some birds were self-taught and some birds went to college for computer science. Even among those groups there were a wide range of experiences and talent. When the birds got together to build their first large application it was a huge disaster. Each bird thought their coding standard was the "right way" and it started to become an issue. One day a wise White Bird came along and suggested that they come up with a common set of coding practices to follow. In addition, the White Bird introduced a few tools to help them conform to a standard and to help find issues and concerns early before they became a huge issue later.

However, during a recent invasion the pigs stole the birds' coding standards document and their code quality tools! As a result, one of the White Birds has been tasked to reclaim what has been stolen. He will use his overwhelming power of quality to help destroy the pigs in order to take back what is theirs.

JavaScript Coding Standards


There are many coding standards out there to choose from. The most important thing is that you pick one and stick to it. If you are working with a team, they should also agree on some standard. If you can't find a standard you exactly agree on, then find one that is close and make some exceptions.

By doing so you'll find that...

  • A developer will be able to make sense of other code more quickly
  • Merges in your code repository won't be as awful
  • Having a standard will actually reduce defects
  • The codebase will feel more unified
  • Disagreements about who is "right" will lessen
  • ... insert your benefit here ...

Here are some of the coding standards that I am aware of...


Addy Osmani (@addyosmani) has a nice post entitled JavaScript Style Guides And Beautifiers that covers some of these styles in depth with examples showing how to abide by the standards recommended.

JavaScript Linting


A linter is a tool that helps find errors and possible issues with your code. In many cases it can help enforce whatever coding standard you chose from the above list.

There are actually several JavaScript linters out there, but the one I like the best is JSHint created by Anton Kovalyov (@valueof). It grew out of a community effort to fork the popular JSLint library written by Douglas Crockford. I've enjoyed watching the project grow and see bugs and new features being added. JSHint has a lot of options that you can choose to opt-in or opt-out of which enables a team to figure out what works best for them.

Some of the standard checks that JSHint can verify include...

  • The use of === instead of ==
  • Using variables that aren't defined
  • Declaring variables that are never used
  • Declaring functions inside of loops
  • And lots more...

For a full list of options see the JSHint Docs.

Some of the more recent additions that I've really enjoyed include:

  • maxcomplexity - Maximum cyclomatic complexity (see following Wikipedia quote)
  • maxstatements - Maximum number of statements allowed in a function
  • maxparams - Maximum number of parameter allowed in a function
  • maxdepth - Maximum depth allowed in a function
  • maxlen - Maximum length of line in code

"The cyclomatic complexity of a section of source code is the count of the number of linearly independent paths through the source code." --http://en.wikipedia.org/wiki/Cyclomatic_complexity


The following errors are generated by JSHint after running it against the above code snippet.


Thankfully you don't have to run JSHint from the website every time to check your code. There are several ways to integrate it into your code editor of choice:


In the Mighty Eagle post we'll talk about another way to use the JSHint from the command line and automatically.

JavaScript Analysis


Code linting is great, but sometimes it is nice to get a high level overview of your codebase and then be able to drill down and analyze small portions of your application.

Thankfully there is a tool called Plato that will analyse your code and provide a visual report where you can view the complexity of your application. The tool runs in Node and you can install it using npm install plato -g.

Once installed you can run the tool on the command line by plato -r -d report myDirectory, which will recursively analyse the code in the myDirectory folder and export the results to the report folder.

If you were to run the report on the jQuery source code it would look much like the following report. As you can see, the average number of lines is decreasing over time, which is good. The maintainability is decent and then a breakdown of the maintainability of each JavaScript file is listed in a bar chart. Further down in the report there are a bar charts for Lines of code broken per file, Estimated errors per file, and also JSLint errors per file.


If you drill into one of the particular files from above you'll see a view that looks like the following. The nice part about this report is that it breaks down each function into complexity and lines of code in a way that is easy to grasp. You can quickly jump to various parts of the file to review the concerns the tool is identifying.


You can view the above jQuery Report from Plato's GitHub repository.

Attack!


The following is a simple Angry Birds clone using boxbox, a framework for the box2dweb JavaScript physics library, written by Bocoup's Greg Smith.

Press the space bar to launch the White Bird and you can also use the arrow keys.


Conclusion


Front-end web applications can get complicated quickly. If your developers aren't all on the same page then things can fall apart in a heartbeat, especially on a large project. Having a unified coding standard and implementing some tools to help find issues before they become a problem can really help to make your project a success.

There are many other front-end architecture techniques that have been stolen by the pigs. Tune in next time as the next Angry Bird takes its revenge! Dun, dun, daaaaaaa!

Wednesday, April 03, 2013

Angry Birds of JavaScript: Black Bird - Backbone

Introduction


A diabolical herd of pigs stole all of the front-end architecture from an innocent flock of birds and now they want it back!

A team of special agent hero birds will attack those despicable pigs until they recover what is rightfully theirs, front-end JavaScript architecture!

Will the birds be successful in the end? Will they defeat their bacon flavored foe? Let's find out together in another nail biting episode of Angry Birds of JavaScript!

Check out the series introduction post for a list of all the birds and their attack powers.


Previous Attacks


Black Bird Attacks


In this post we will take a look at the Black Bird who will use the organized approach of the Backbone.js bomb to fight these porkers. Slowly, one by one, the birds will take back what it theirs to keep!

What Was Stolen by the Pigs?


The birds used to write their jQuery code like it was a tangled smorgasbord of worms. They would mix up their views, models, and presenter logic all together in a big interconnected pile of grubs. After a while one of their ancestors, a Black Bird, introduced the Backbone.js library and showed them a different way to think about developing front-end web applications. However, during a recent invasion the pigs stole Backbone.js from the birds and carried it back to their filthy sty.

One of the black birds has been tasked to reclaim what has been stolen. He will use his explosive power of organization to help destroy the pigs in order to take back what is theirs.

Tangled Smorgasbord of Worms


Let's take a look again at the following application that the Blue Bird dealt with in a previous attack. Instead of adding messages to untangle the mess we are going to introduce how using Backbone.js can help us out. Here is the running application below...

It appears Plunker is not embedding correctly at the moment. The application is a simple Netflix search interface that will show the results from Netflix. If Plunker doesn't start working soon I will move the demo somewhere else. Sorry for the inconvenience.



And to refresh your memory, here is the supporting code used for the above web application. You should notice that a lot of concerns are all being mixed together (DOM events, Modifying the View, AJAX Communication, etc...)


Do you see the problem? It is so tempting to write code like the above, but I hope you see that it can be a bear to work with and maintain. Don't worry, we have all written code just like the above. The good news is that we don't have to continue to write it that way. Let's take a look at what Backbone.js is and how it can help us out in this situation.

There are many other MV* front-end frameworks (Knockout, or AngularJS, EmberJS, & others) that could also bring structure to the above code. I would encourage you to pick a tool that you can be productive with and get comfortable with it.

Backbone.js Basics


Backbone.js has several pieces that can all work together to make a web application. You don't have to use all of these components, but they are available if you choose to use them.

  • Model - Represents data and logic surrounding it
  • Collection - Ordered sets of Models
  • View - A module backed by a Model with a render method
  • Router - Mechanism to provide linkable, sharable URLs
  • Event - Observer Eventing module
  • History - Provides the ability to maintain history (back button support)
  • Sync - Extendable component providing RESTful communication to the server

Refactoring the Tightly Coupled Code


Let's take a stab at refactoring the above jQuery mess and use Backbone.js to split out some of the various concerns.

I'm not going to dive into all of the above pieces in this post, but will focus on 3 of the main pieces (Models, Collections, and Views). I'll touch on some of the Sync concerns, but as part of the other topics. I'll have resources listed at the end if you want to dig deeper into any of these topics.

RequireJS


Before we get into the Models, Collections, and Views I want to show you how we took out all the scripts from the index.html page and used RequireJS to help us out.

If you've never seen RequireJS before then you might want to check out the previous Yellow Angry Bird Post about RequireJS.

main.js


The above code is defining the paths for jQuery, Underscore, Backbone, Postal, and Bootstrap. We needed to shim Underscore, Backbone, and Bootstrap since they are not defined as AMD modules.

Then the require function is called to request a set of dependencies before the callback is invoked. At that point, jQuery and all the other views and models will be ready for usage!

Models


We are going to make 2 models (Search and Movie) to represent the above application.

The following Search Model is really simple and its main job is to respond when the term property has changed. We are using Backbone's events (Observer Events) to listen to changes on the model and then propagating the message to Postal.js (Mediated Events). For more information about those terms and how they are different you can reference the Blue Angry Bird Post about events.

search.js


The following Movie Model doesn't have a lot going on as well. It's main purpose is to parse the data returned from the server and map the results to something a little more manageable. In this case we are only concerned with the releaseYear, rating, and name properties.

movie.js


Collections


As we described above, collections are just a set of models. The following code is just a set of Movie models. The collection is where you define where to get the list of models from the server. The back-end for this application is Netflix and their endpoint is a little complex so we are using a function to dynamically build that URL. We also defined a parse method to get directly to the array of contents that will be mapped to Movie models. Since this AJAX call will be using JSONP we also needed to override the sync method and provide some additional options.

movies.js


Views


I see the View as more of a Presenter than the typical MVC View you might normally think of. Anyway, We have 2 views in this application that we will briefly look at.

The following SearchView handles the interactions with the DOM and the Model. The events property primarily is used to listen to DOM events and in this case is watching for clicks on the button or previous search links. Changes to these elements will be stored in the model as term. The initialize method sets up some events listening for changes in the term property. If term changes, then portions of the UI will change accordingly.

search-view.js


The MovieView below is a little different than the above view. The first thing to point out is the weird text!movie-template.html. I am using the text.js plugin for RequireJS that let's us pull text resources as part of the dependency chain. This is really helpful for markup files used when using a templating engine or possibly a CSS file that is associated with a particular widget. Inside of the initialize method we are subscribing to a change in the term and then asking the collection to fetch the information from the server. The render method gets called after the data is retrieved from the server and we use Underscore to template the results to the DOM.

movie-view.js


The following is the template file in case you were wondering. I'm using Underscore's templating engine which is similar to John Resig's micro-templating implementation that he wrote years ago. There are other templating libraries available, but I used this one because it comes with Underscore which is a prerequisite for Backbone. If I needed something more featured I would have used Handlebars instead, but that is a story for another Angry Bird ;)

movie-template.html


Additional Resources


I only scratched the surface on all the things you can do with Backbone.js. If you are interesting in learning more about these concepts you may want to look at some of the following resources.

The following resources were taken from the Beginner HTML5, JavaScript, jQuery, Backbone, and CSS3 Resources blog post.


Attack!


The following is a simple Angry Birds clone using boxbox, a framework for the box2dweb JavaScript physics library, written by Bocoup's Greg Smith.

Press the space bar to launch the Black Bird and you can also use the arrow keys.


Conclusion


Front-end web applications can get complicated quickly. Before you know it you have a pile of interconnected mess if you are not careful. Thankfully Backbone.js provides components to help you split out your application into consumable pieces that each have their own purpose. Thank you Black Bird for returning Backbone back to the birds. They will be able to rest easier knowing things are organized and in their proper place.

There are many other front-end architecture techniques that have been stolen by the pigs. Tune in next time as the next Angry Bird takes its revenge! Dun, dun, daaaaaaa!