Tuesday, May 29, 2012

JSGentleman Rule #4: write libraries

We all know that decoupling is a good thing and the best way to do that when writing an application is to write libraries instead of application code.

What you can do now is to take parts of code that you have written, minimize it's dependancies and then generalize the input. Viola - a library that can be used in future projects.

Whenever I start a new project I try and identify parts of the program that can be abstracted, give it an API and make sure I don't pull in dependancies from elsewhere in the program (unless necessary and explicitly stated). Working like this helps decouple the project and stating dependancies and an interface will help future developers working on your project, but there are also more benefits.

Writing as a library will allow you to easily open-source non-critical parts of your project which can help the community, promote your company, and get feedback to improve the code. It also means that other people will be looking at your code which means you'll stay a bit more alert about writing good clean code, documentation and testing.

When working on your new library you may also put in extra functionality that isn't necessary in your project. This is good practice as it can help you in future iterations. I find sometimes I like to work on a library separate of a project to add in new features, only to then realize I can actually use these new features in the product. It's a win-win, and if you're using a minified like Closure-Compiler you won't have to worry about bloat as it removes unused functions.

The final reason is that it's a good abstraction. You might start writing out parts of the program only to realize that someone else has done a better job and because you started with a decoupled design it shouldn't be too hard to swap out for another library.

So next time you start on a new part of your program think about how you can generalize it, then stick it up on github.

Thursday, May 24, 2012

using JQuery functionally

I was looking at the code on a site recently and it was all blocks of JQuery. The first thing I saw was that there was a lot of lines that were almost the same - basically that there was a selector then 3-4 methods chained off it. First thing I thought was why not put that in a function, something like:

var doStuff = function(selector) {
$(selector).method1().method2().method3();
};

which would allow you just to call the doStuff method with the selector. It then hit me that we're just abstracting away the functionality of JQuery which is a good thing. Then I wondered if I could change it in to functional style (without writing the whole of JQuery).


The first thing is to realize is that Javascript allows us to change scope using call or apply. You can pretty much write OO code in a functional style using those. So basically these are the same:

// OO
obj.method(param);

// Functional
Obj.prototype.method.call(obj, param);

Now JQuery makes it easy to get to it's prototype for adding plugins. This mean we can call a jquery method like:

$.fn.method.call($(selector));

Ah, now we can see that the $() is a function itself. So now we can use composition f.g(x) == f(g(x)):

compose($.fn.method, $)(selector);

There is still a problem though, compose will call the method with a different context and pass in the JQuery object as the first argument. There are two solutions and they're both fairly useful. The first is that we could have a special bind for JQuery methods:

var $bind = function(fn) {
  var args = arguments;
  return function($object) {
    return fn.apply($object, args.splice(1));
  };
};

so we could bind the method and pass it in to compose or even just use it:

var $method = $bind(method);
var $elems = $(selector);
$method($elems);

// or

compose($method, $)(selector);

The major difference is that $bind will take in other arguments when bound, whereas compose methods only accept one argument.

But we can probably do on better. We could just check to see if it's a jquery function and apply it inside compose. So let's make $compose:

var $compose = function(var_args) {
  var args = [].slice.call(arguments);
  return function(arg) {
    var ret = arg;
    for (var i = args.length; i; i--) {
      if(args[i - 1] in JQuery.fn)
        ret = $bind(args[i - 1])(ret);
      else
        ret = args[i - 1](ret);
    }
    return ret;
  };
};

Now we can just pass in the jquery methods to compose as they are. So let's compare:

// OO style
var doStuff = function(selector) {
  $(selector).method1().method2().method3();
};

doStuff(selector);

// Functional style
var doStuff = $compose($.fn.method3, $.fn.method2, $.fn.method1, $);

doStuff(selector);

So there we have it. JQuery being used functionally. I haven't tested or tried any of the code so not sure if it will just work but hopefully it's enough to get you interested and I'd love to see what other people can do with it. Keep in mind though that compose functions take one argument so it's great for things like $.fn.hide but you may want to bind other methods:

var makeRed = $bind($.fn.css, {'background': 'red'});
compose(makeRed, $)(selector);

You may want to make some improvements in $bind and $compose like automatically wrap whatever is passed in with the JQuery object.

Thursday, May 17, 2012

Starting Closure

There has never been a better time to start using Closure.

The closure set of tools has been open sourced for a couple of years now and the last piece of the puzzle has landed, namely Closure Stylesheets. Now there is a full set of tools that are out there for you to use, not only that but the tools have been out long enough that there is help available.

Closure tools has been created fir a large team to create large applications. This has been the main hurdle to new developers wanting to learn. Most new developers will begin to learn closure at work in a team. Luckily there are now tools out there to help single programmers start for any size of project. Here is what you need to start:

Closure: The definitive guide

If you want to start with the tolls a great way to start is to understand the thinking behind it. The book will give great insights in to how the tools work and how you can use them. There are great books out there for every library, and closure is no exception.

Plovr

Plovr is a tool written by Michael Bolin and makes using the library, compiler, templates and tests a breeze.

G-Closure

I'm guessing you already know jquery. Let's face it, it's almost analogous to javascript. One of the concerns that people have is that the closure library is long-winded. The library was written in a functional style and namespaced so you have to type out the namespace then the function and pass in the object you need. JQuery is a bit easier as you already have the object and you can just call functions on that, not only that but you have the famous chaining API. G-Closure lets you use DOM, Array and Object functions in the closure-library like you would JQuery. This means you don't even need to know the library to start, if you know jquery you can already build a webpage using the library.

PlastronJS

You probably use backbone.js or some other MVC. Well now closure tools has an MVC too, PlastronJS. If you read this blog you should know all about it by now. It's designed to be familiar but also, like the closure library, have many more features you can choose to call on or disregard depending on your needs.

Et al.

An honorable mention should go towards the closure coffeescript fork which does a great job removing the "wordiness" of the library.

But Wait!

If you were about to go hop off and try Closure Tools for the first time I recommend waiting just a little bit more. Closure Tools now has a meetup which means the community is going to get stronger and the toolset is going to get easier. In fact I'll have another little project to announce very soon that should help you on your way. In the meantime I recommend starting by reading the book and keeping your eyes peeled on this blog for further announcements.