Google Buzz First Reactions

So Google just launched their latest product: Google Buzz, which is starting to get some mixed reviews. I myself am still a bit mixed on its purpose and actual value. I’ll do my best to sum up my views below, but if you’re impatient I can sum it up for you here:

It’s pretty cool… It just needs some work.

The Good Stuff

Deep conversations

It’s wonderful to see them taking what works well on reader and expanding upon it to allow for deep conversations to emerge. Look at this simple experiment:

http://www.google.com/buzz/abinandanan/d4zdttKNZSN/I-want-to-see-how-this-appears-in-Buzz-Materials

Nice right? That’s what I thought too. The amount of discussion which can emerge from this is impressive.

The lack of content length restrictions and the ability to comment inline are two key differences from Twitter. Much like a normal blog post, this allows someone to post a statement and other folks to comment on it. Sure, you can @reply on Twitter, but you’ll need to do some work if you want to see the conversation in context.

Progressive Social Changes

This is just one notch in Google’s social bedpost and I think it’s fantastic. I love to see how Google is using all of these products to allow their users to share and become social.

This is especially nice because damn near everyone has a Gmail account now which means that damn near everyone is logged into their social network. I’ve always said that the key to any good social network is that sharing content must be next to effortless. They’ve done a great job here.

That said, there are also some serious privacy concerns too. Which I mention below.

The Attention to UI Design

Everyone who has had a Gmail account from the start, raise your hands.

Remember how awfully ugly it was? I remember bringing that up as an example in a lecture once to back up my point on form following function. Now fast forward in time about 5 or 6 years and look where we are.

Ok, so maybe Gmail hasn’t changed much they certainly have started to add subtle elements which do stand out. Drop shadows, cleaner branding, larger search boxes, clearer calls to action. You get my drift.

And if you look at two of their most recent radical products, Wave and Buzz, you’ll see just how far they have come in terms of UI design.

I for one appreciate this.

The Bad Stuff

It just doesn’t work

Were you like me and didn’t see any change in your Gmail? Even after clicking the “Try Buzz in Gmail” link a few times you still saw no effect right?

Same here. You know what the problem was? Gears. Something with Gmail’s offline settings and Gears causes the update to simply not work. I had to disable offline storage in order to see it work properly.

Note: I was using FF3 Mac. Other browsers seemed to work fine.

Inbox … Buzzbox … What?

Maybe this is clarified somewhere in their documentation, but nobody reads that crap. People just jump in and want to use it. Like me.

So why is there a Buzz box (for lack of a better term) if buzz also shows up in my inbox? Sorry guys, I just don’t get this.

With so much attention to details in the UI, I think this is a serous oversight.

Tweets go in, but none go out

This is complete crap. Why can’t I tweet from Buzz?

Ok, that was a little harsh. But I hope you can understand where I’m coming from. As someone who spends a great deal of time on Twitter and Gmail daily, having the ability to save some time would be really nice.

Looking deeper into things, once could see this as yet another one of Google’s famous industry disruption tactics. If this is the case, I think it’s in very bad taste. While I love to see Google using their muscle to push industries like satellite navigation and broadband services to the next level, using it shake up Twitter is just wrong.

Hopefully I’m wrong about that though.

Privacy, hello?

When I first got it working (see below why I struggled), I noticed so many new people who I’ve never seen before. The default privacy settings for Buzz allow me to see my follower’s most contacted friends and vice versa.

While there are probably aren’t any technical exploits which can emerge from this, the social engineers in the crowd are probably praising Google for this irresponsibility.

What’s worse is that I think I’m seeing a pattern emerge. Look here:

http://facebook.com/mgirouard

If you’re not logged in, or not my friend, you see lots of information about me, what I’m interested in and also the first and last names of my friends.

Please, don’t bother mentioning that these can be adjusted with privacy settings. Lets get real here: these are not reasonable defaults.

What do you think?

Personally, I think that this is definitely an interesting product launch, but as I mentioned, it needs some work. The key area where I’d like to see some improvement is in sharing content with external sites, not just keeping it inside Google’s network.

I’m curious to hear your thoughts on this too.

Posted in Opinion | 6 Comments

Responsible JavaScript: Using Switch

JavaScript, like most languages of the C-genus, has a switch statement which is a really handy alternative to the standard if conditional. switch is a bit of an underdog in the world of conditionals, usually only coming out when there would normally be many else statements.

Interesting Features

Fallthrough

switch has a really interesting behavior called fallthrough which is just as dangerous as it is powerful. Consider the following code which:

function dateSuffix(date) {
    switch (date) {
        case (1):
        case (21):
        case (31):
            dt = "st";
        break;

        case (2):
        case (22):
            dt = "nd";
        break;

        case (3):
        case (23):
            dt = "rd";
        break;

        default:
            dt = "th";
    }

    return date + suffix;
}

While fallthrough is really useful, the problem with fallthrough is that it’s implicit. There is no clue to the developer that fallthrough has actually occurred other than his data being modified, or worse, his program stops working.

Flexibility Through Expressions

One of the most powerful features of JavaScript’s switch implementation is that the entire control structure is based on expressions: The switched conditional can be an expression and the case values may also be expressions. Unlike the standard if statement, the conditional blocs (the case statements) are not enclosed in curly braces. Instead they too are expressions. This makes conditional breaks possible.

...
case (someValue):
    if (isProperFormat(someValue)) break;

    someValue = formatValue(someValue);
    // intentional fallthrough
...

It should also be noted that because case blocks lack the use of curly braces, accidental fallthrough is quite easy. Simply forgetting the break statement will cause fallthrough and the next case will be evaluated.

Alternatives

The Simple Conditional

Conditionals are my personal favorite as they are explicit in their meaning. Code which is easier to read usually makes for less bugs down the road.

function dateSuffix(date) {
    var suffix;

    if (date === 1 || date === 21 || date === 31) {
        suffix = 'st';
    }
    else if (date === 2 || date === 22) {
        suffix = 'nd';
    }
    else if (date === 3 || date === 23) {
        suffix = 'rd';
    }

    return date + suffix;
}

Lookup Tables

Lookup tables are a slightly more advanced version of switch statements. These are my personal favorite as they are generally much more flexible and can be crafted to be modified dynamically at runtime.

function dateSuffix(date) {
    var suffixMap = {
        'st' : (date === 1 || date === 21 || date === 31),
        'nd' : (date === 2 || date === 22),
        'rd' : (date === 3 || date === 23)
    };

    for (var suffix in suffixMap) {
        if (suffixMap[suffix]) {
            return date + suffix;
        }
    }
}

Best Practices

Despite some of the issues with switch, none of these are JavaScript-related. Rather these are simply issues with this control structure in general. It still remains that this is a very useful alternative to a standard conditional that, when used properly, can help improve the readability of your code.

Here are a few simple guidelines to keep in mind:

  • case statements work best for short one-line operations. The more operations that follow a case statement, the easier it is to forget to add a break. If you find lots of nested operations inside of a case statement, you’re better off using one of the alternatives above.
  • On the same note of preventing accidental fallthrough, make sure to always maintain proper indentation while working in case statements. I always add my break in before writing the actual code which gets executed.
  • If fallthrough can’t be avoided, always document it inline with // intentional fallthrough or something similar. This will remind yourself (and other developers) that it is not a bug.
Posted in JavaScript | 1 Comment

Responsible JavaScript: Incrementing and Decrementing

One area of JavaScript which has gotten a lot of negative attention lately is the increment and decrement operators. To be clear, much (if not all) of this discussion can be traced back to JSLint’s intolerance of them.

To understand this completely, you need to understand that JSLint is a project of Doug Crockford, a well known JavaScript architect with a reputation for his strict coding standards. Naturally, all of his recommendations have made their way into JSLint, including the topic of today’s post.

An Extreme Example

The ++ (increment) and — (decrement) operators have been known to contribute to bad code by encouraging excessive trickiness. They are second only to faulty architecture in enabling to viruses and other security menaces. There is a plusplus option that prohibits the use of these operators.
Douglas Crockford

Those are some serious words, but Doug has a good point: If you aren’t careful, your code can get pretty messy with fancy expressions. For example, all of this is valid JavaScript:

var a = 1;
var b = 2;
var c = 3;

a++ + b;
a + ++b;
a + + + b;

console.log(a, b, c);

Its easy to look at an isolated example such as the one above and say “sure, but nobody writes code like that in real life.” Sorry, but you would be wrong. Just ask Google

The sad fact of the matter is that we all write code like that at some point. It looks like it’s alright when we write it, but then when it comes time to maintain it or hand it off to another developer for them to figure out.

The other side of the coin

While the above code is frightening, the reality is that there are much more common uses of the increment/decrement operators. In fact, for most people, their first experience with these operators is in the simple for loop.

for (var i = 0; i < foo.length; i++) {
    bar.doSomething(foo[i]);
}

While there may be better ways of iterating arrays, code like the above is so common that it’s instantly recognizable.

Another, quite common example is when concatenating numbers to strings in JavaScript. Consider the following snippet:

var grandTotal = myXmlDoc.getElementById('grand-total').nodeValue;
var statusMessage = 'Your card will be charged $'+ (+grandTotal).toFixed(2) + '.';

Since grandTotal ins’t a number, we need to convert it using the + operator. Unfortunately, that is also the concatenation operator which makes for an interesting mess of symbols.

There is an interesting thing to note here: the use of parenthesis. In this case, they are required, however in some of the more ambiguous situations (above) they can help clarify some complicated code.

There are plenty of other ways that incrementors and decrementors can be used safely. Yes, it is very possible to write bad code with these operators — and they certainly do make it much easier to make serious mistakes. However, instead of eliminating them entirely from your code, how about simply using some common sense? Simply put, there are just as many ways these operators can simplify your code as there are ways they can overcomplicate it.

Complex incrementing or decrementing operations (like all complex code) should be handled responsibly. Here are a few best practices to keep in mind:

  1. Move type conversions, long series of concatenations, and any other tricky code into a helper method.
  2. Know the difference between pre-incrementing and post-incrementing and use them appropriately.
  3. Really think before nesting incrementors or decrementors in expressions such as array key references or return values.

Related Links:

Posted in Design Patterns, JavaScript | Leave a comment

Talk: Responsible JavaScript

In case you haven’t noticed, I’m just past the halfway mark on my series on Responsible JavaScript. If you haven’t been following it, be sure to check it out — there’s some good stuff in there.

Tonight, I’ll be giving a talk at Refresh NYC on this very topic. If you’re in NYC, I hope to see you there! If not, bookmark this post as I’ll be posting the slides here after the talk.

Forget what you know about JavaScript… We’ve been told of all its glories and all of its failings. The fact of the matter is that it’s a greatly under-appreciated language with a few well-documented mistakes.

Most of us are quite familiar with best practices in JavaScript programming; the most common of which are to avoid the “bad parts” at all costs. This talk will discuss many of these bad parts in depth and show you ways that you can continue using them in your programs responsibly.

You can RSVP on the Meetup page.

Update

For those interested (or for those who missed it) you can find the slides on Slideshare.

Posted in JavaScript, Talks | Leave a comment

Responsible JavaScript: Using ‘this’

As I’m sure we are aware by now, JavaScript is quite a remarkable language. One of the more interesting (and frustrating) aspects of the language is it’s object oriented nature. It borrows a considerable amount of its syntax from Java including the this keyword, which is what I’d like to discuss today. However, unlike Java (and other object oriented languages), the identity of this isn’t always clear.

this is a popular keyword for referencing the current object in a object oriented languages. What’s interesting though, is that scope is relative in JavaScript. This means that this could refer to any arbitrary object.

The ambiguity of this is the source of lots of misunderstanding so I’ll attempt to clarify things a bit here. Here are a few rules to keep in mind:

  • this tries to refer to the object in which it is used.
  • If used in a method in an object’s prototype, this will refer to the object’s instance.
  • If used in an event handler, this will should refer to the element on which the handler is used.
  • These rules all go out the window when Function.call or Function.apply is used.

The first two rules should be obvious, however the second two deserve an explanation.

Events can get tricky

While the above examples are rather obvious, event callbacks get to be a bit tricky. To help us understand this concept a little better, lets assume the following function is defined:

var eventCallback = function () {
    console.log('Am I the window?', window === this);
    console.log('Am I a HTMLElement', !!this.nodeName);
};

this in the Standard Event Model

Event handers (in standard event models) will execute in the context of the event’s target element

// false, true
document.getElementById('some-link')
    .addEventListener('click', eventCallback, false);

this in the Microsoft Event Model

Unfortunately, in the Microsoft world, things are different. Event handers are still executed in the global context.

Note: This only applies to IE6 and below.

// true, false
document.getElementById('some-link')
    .attachEvent('onclick', eventCallback);

this in the Netscape Event Model

The Netscape event model simply copies a function into an object. this will always refer to the parent object (the elemet) as expected.

// false, true
document.getElementById('some-link').onclick = eventCallback;

Breaking the rules with call and apply

Since functions are objects in JavaScript, functions also have methods. Two very interesting methods on all functions are call which allows you to dynamically call a function with a fixed set of arguments, and apply which does the same thing except an array is used to pass argument values.

Function.call and Function.apply’s signatures look like this:

Function.call(Object scope [, mixed param [, ... ]]);
Function.apply(Object scope [, Array params ])

The interesting part of both these methods is the first parameter: scope. This allows you to pass an object (yes, any object) in to be used as the scope in which the function is called. This is not only incredibly useful, but it’s also a way that many libraries and frameworks normalize browser inconsistencies (like events as mentioned above).

Consider the following:

var whoAmI = function (someObject) {
    console.log(this === someObject);
};

var someElement = document.getElementById('some-element');

whoAmI(window);             // true
whoAmI(someElement);        // false
whoAmI.call(someElement);   // true
whoAmI.apply(someElement);  // true

Best Practices when Using this

  • When possible, try to keep this usage to a minimum. Eliminate it if possible.
  • When working with event callbacks, use a library (like YUI or jQuery) which automatically corrects the scope of the callback. You can roll your own, if you use Function.apply.
  • When developing libraries, always keep event callbacks separate from application methods. For example, a callbacks property.
  • Always functions which run in a different scope than expected.

Related Links

Posted in JavaScript | 2 Comments

Responsible JavaScript: Using Factories

Wikipedia has a wonderfully dry definition of the factory pattern:

The factory pattern is a creational design pattern used in software development to encapsulate the processes involved in the creation of objects.

The creation of an object often requires complex processes not appropriate to include within a composing object. The object’s creation may lead to a significant duplication of code, may require information not accessible to the composing object, may not provide a sufficient level of abstraction, or may otherwise not be part of the composing object’s concerns.

Some of the processes required in the creation of an object include determining which object to create, managing the lifetime of the object, and managing specialized build-up and tear-down concerns of the object.

Essentially what we’re talking about here is complexity management. Complexity is disease that infects all programs and APIs at some point and JavaScript is certainly no exception. Just look at the awful code it takes to reliably create an XMLHttpRequest instance:

var XHRFactory = function () {
    if (window.XMLHttpRequest) {
        return new XMLHttpRequest;
    }
    else if (window.ActiveXObject) {
        var xhr, axo, ex, objects;

        objects = ['Microsoft', 'Msxml2', 'Msxml3'];

        for (var i = 0; i < objects.length; i++) {
            axo = objects[i] + '.XMLHTTP';

            try {
                xhr = new ActiveXObject(axo);
                return xhr;
            }
            catch (ex) {};
        }

        throw 'Unable to create XHR object.';
    }
    else {
        throw "XMLHttp is not supported.";
    }
};

To make matters worse, JavaScript has a nasty constructor implementation which if used improperly, can cause lots of hard to trace errors. For example, this problem which I outlined in a previous post on the topic:

var Person = function (name, location) {
    this.name = name;
    this.location = location;
};

var mike = new Person('Mike G.', 'NYC');
var alex = Person('Alex H.', 'NYC');

Paste that block into firebug and tell me how long it takes you to find the root cause of the problem.

Not only do factories help manage complexity, they also manage dangerous problems with the language. Simply put, factories in JavaScript should be a considered a best practice of responsible programmers.

Update: Advanced Factories

Ok, enough bashing on JavaScript. Lets switch gears a moment and talk about one of the more interesting aspects of the language: its functional nature.

JavaScript is a functional language and as such, functions can be treated as you would any other data type. You can store functions in variables:

var hello = function () {
    console.log('Hello, world!');
};

… pass functions as arguments to other functions:

var foo = document.getElementById('foo');

foo.addEventListener('click', function(event) {
    console.log('You clicked foo.');
}, false);

… and even return functions from functions:

var functionFactory = function (name) {
    return function () {
        console.log('I am ' + name + '. Thanks for running me');
    };
};

mike = functionFactory('Mike');
owen = functionFactory('Owen');

mike();
mike();
owen();

functionFactory('cool eh?')();

Function factories have so many uses. The deeper you go into JavaScript, the more you find yourself using function factories. As Peter Michaux has shown us via his lazy function pattern, it can be a fantastic way to save on resources. Likewise, we can take the same concept and apply it in a way I like to call Load Time Configuration.

Take a look at my XHR code above. Immagine the pain that your browser has to go through every time you call that function. First it has to check to see if it supports the standard XHR object. If not, then it has to go though all the foulness of MSXML juggling.

Lets simplify things a bit and make it so that it bakes the appropriate function on page load. This will eliminate the initial check:

var XHRFactory = (function () {
    if (window.XMLHttpRequest) {

        return function () {
            return new XMLHttpRequest;
        }

    }
    else if (window.ActiveXObject) {

        return function () {
            var xhr, axo, ex, objects;

            objects = ['Microsoft', 'Msxml2', 'Msxml3'];

            for (var i = 0; i < objects.length; i++) {
                axo = objects[i] + '.XMLHTTP';

                try {
                    xhr = new ActiveXObject(axo);
                    return xhr;
                }
                catch (ex) {};
            }

            throw 'Unable to create XHR object.';
        }

    }
    else {

        return function () {
            throw "XMLHttp is not supported.";
        }

    }
})();

As you may have imagined, this is also useful when dealing with the event registration problem. I’ll save that for a future article. In the mean time, consider that an exercise to practice with.

Enjoy!

Posted in JavaScript | 1 Comment

Responsible JavaScript: Prototype Modification

JavaScript is a fully object oriented programming language that supports multiple inheritance models. At the heart of it all, JavaScript uses prototypal inheritance. Even the default types (String, Boolean, Number, …) are objects themselves. When you “extend” something, you don’t extend a class — instead, objects inherit directly from other objects.

Some libraries (Prototype, for example) make heavy use of modifying native object prototypes. This has the instant effect of adding significant functionality to all instances of the native objects.

// Create a new array instance and populate it with some data.
var a = ['foo', 'bar', 'baz'];

// Modify Array's prototype to include new functionality
Array.prototype.each = function (callback) {
    for (var i = 0, l = this.length; i < l; i++) {
        callback(this[i], i);
    }
};

// Even though 'a' was defined prior to the pototype modification,
// the effects are visible. This is the power of prototypal inheritance.
a.each(function (value, index) {
    console.log(index + ' === ' + value);
});

While the temptation is great, responsible developers should think twice about modifying native object prototypes. One may argue that “additive” methods pose no harm. Still, by adding behavior, your casting your dependencies on the language itself thereby making documentation and debugging challenging.

What’s even worse is when developers get clever and modify Object.prototype. This of course has the effect of modifying all objects of all types. The most obvious repercussion of this is that it breaks the for..in pattern which is commonplace in most JavaScript applications

Object.prototype.foo = function () {
    console.log('foo');
};

var o = {'hello':'world'};

for (var i in o) {
    console.log(i + ' === ' + o[i]);
}

At this point, the pros in the crowd will yell “yeah, you should be using hasOwnProperty.” And rightfully so, as that is the only way to insure that we’re dealing with members local to our object in question. But what if we want to get an aggregate list of properties local and inherited? If you’ve futzed with Object.prototype, you’ll have to use recursion … I hope you’re happy now.

Don’t Modify. Extend.

Instead of modifying the native object, simple create a new data type by extending it as you would any other object.

var MyArray = function () {};
MyArray.prototype = new Array;

var ma = new MyArray;
ma.push('foo');
ma.push('bar');
ma.push('baz');

console.log(ma.join(','));

This technique offers the same end result without compromising the integrity of the application. It’s more portable and allows for easy documentation. This is also the natural action if you are familiar with classical inheritance. While applying classical development methodologies to languages such as JavaScript is generally a bad idea, in this particular case it’s the responsible thing to do.

Posted in JavaScript | 5 Comments

Responsible JavaScript: Namespaces

Continuing in my series on Responsible JavaScript, today’s discussion will be on the responsible use of namespaces.

I’ve covered namespaces in JavaScript before, so I won’t go into the mechanics of how to accomplish this. Instead, I’d like to focus on responsible namespace creation and organization.

We’re told quite often that we should namespace everything. I myself am one of the loyal followers of this philosophy, but I also think that it’s important to keep ourselves in check.

Have you ever written anything that looked like this?

fooCom.utils.appManager.myApp.widgets.contactForm.validate();

Ok, so maybe that’s a bit extreme. Maybe not. Over-engineering your namespaces can be just as problematic as not using them at all.

How to responsibly namespace your code

I recommend you always do the following with your namespaces:

  1. Use a namespace wrapper utility to create your namespaces
  2. Segregate application namespaces from library namespaces
  3. Organize libraries component groups
  4. Organize applications into functional groups

The Namespace Utility

Creating namespaces are as simple as creating JavaScript objects.

var myApp = {};

This technique works really well until you start having several apps share a common namespace. If all your apps start off with var myApp = {}; each new app will clobber the previously defined one.

Of course, you can prevent this by checking if the object exists already…

var myApp = myApp || {};

… but who wants to do that at the top of each of their applications? Furthermore, this problem becomes worse when you need to check for nested namespaces.

YUI2 has a wonderful implementation of a namespace utility which will create namespace objects for your application without clobbering existing objects. You can pass it a namespace like myApp.widgets and it will be smart enough to create myApp for you if it doesn’t already exist.

My own version looks like this:

var namespace = function (namespace) {
    var components = namespace.split(/[^a-z0-9]+/ig);
    var context = window;

    for (var i = 0, l = components.length; i < l; i += 1) {
        var component = components[i];

        if (!context[component]) {
            context[component] = {};
        }

        context = context[component];
    }

    return context;
}

Application/Library Segregation

Another common problem is when your application namespace shares the same namespace as your library. This is my biggest problem with the YUI2 architecture because it can quickly lead to massively nested namespaces.

Your application should stand on its own. In the unfortunate, but far too common cases where a library must be replaced, having a standalone application object will save you lots of headaches.

On a similar (and probably less important) thought, it should be noted that developers tend to name libraries after companies rather than giving them names of their own (as you would a project, for example). Companies die, get bought/sold, etc. Do yourself a favor, don’t name your libraries after your company or worse, tie your applications into your companies namespace. You’ll regret it someday.

Library Organization

If there’s one place in code where it’s probably ok to have nested namespaces, it would be library code. Libraries (please note that I didn’t say framework) should be designed so that there is open sharing of components. Wherever there is an overlap of tools, generally a sub-group will need to be created.

I recommend that you avoid the general util bucket unless you really can’t think of anything better.

Application Organization

Applications, on the other hand, are usually fixed modules or running instances of programs in which your utilities live in a common context. Yes, it’s ok to have your util bucket here as there are likely to be lots of utilities your application makes use of throughout it’s execution.

Don’t over-think it

Engineers of all kinds have a common flaw of always trying to improve upon something. Programmers will always try to find a better way to write and organize their code. The key here is to find the balance.

All programs will start off having perfectly organized namespaces, but with time they will deteriorate. Having a system like the above helps to prevent it from falling apart entirely.

Posted in JavaScript | Leave a comment

Responsible JavaScript: Globals

We’re always told that globals are evil and that we should never use global variables. While it certainly is true that globals offer a considerable performance hit, it is nearly impossible to avoid global variables.

There are two basic types of applications a programmer can write in JavaScript: simple ones and not so simple ones. Think of simple applications as the 5 or 10 liners that generally wind up a the bottom of a page (yes, we all know JavaScript should be external but everyone breaks this rule from time-to-time). Likewise, not so simple apps are everything else.

Avoiding Globals Entirely

If you find yourself writing simple apps frequently, you can generally get away without creating any additional globals by wrapping your application in a self-invoking function:

(function () {
    var popupCallback = function (event) {
        window.open(this.href);
    };

    var anchors = document.getElementsByTagName('a');
    var length = anchors.length;

    for (var i = 0; i < length; i++) {
        var a = anchors[i];

        if (a.getAttribute('rel') === 'external') {
            a.addEventHandler('click', popupCallback, false);
        }
    }
})();

Of course, the moment you need to do anything more complicated than this, you’ll probably need to create a global variable to link libraries against.

When You Can’t Avoid Globals

In the cases (which are more often than not) where you can’t avoid creating global variables, it’s best to set some rules up so that you can avoid going crazy.

First off, forget the notion that you will have only one global variable. The moment you start introducing libraries into your application, you’ll be adding global variables.

I recommend using the following rules:

  1. Namespace everything
  2. One global name is allowed per library or framework (jQuery, YUI, etc)
  3. One global name is allowed per application (contactForm, shoppingBasket, searchBar)

Namespaces

I’ve written about JavaScript namespaces in the past be sure to read up on that. These should be common practice by now, but there’s still some best practices which need to be discussed with regards to responsible namespace creation. Hang tight, I’ll be discussing these in depth in my next post.

Libraries and Frameworks

Lets hope you’re using a modern framework like jQuery or YUI which actually respects the global object and does its best to not pollute it. With this in mind I allow one global object per library.

So for example, if I include jQuery, that creates the window.jQuery object (lets assume I have compatibility mode set, so it doesn’t create the $ object — which I will also be talking about later too).

I also may want to include my own home-grown framework to make use of some utilities I wrote. This makes two library members which I can now reference.

Get the idea?

Applications

Much like libraries, it’s also quite common to have multiple applications running simultaneously on a single page. Banners, form handlers, custom UI elements, you name it. When these things need to communicate with each other, it becomes difficult to not use global variables.

Sure, if you have complete control over each component, and enough foresight to do so, you could probably write some clever application framework with all the right hooks so all these components can live in harmony together. But the moment the account person comes through your door demanding they need to hook in yet another third party component, all hope is lost.

Minimize, not eliminate

To conclude, I’d say your time as a programmer is best spent minimizing global variables rather than finding clever ways to eliminate them.

Don’t mistake this for being reckless. Just because JavaScript’s original intent was for everything to be globally linked doesn’t mean that it’s actually a good idea.

If you can eliminate them entirely, great. If you can keep it down to one or two, that’s not bad either. If you have 10 globals and you’ve followed the rules above you’ve done your best and are a responsible JavaScript programmer. Treat yourself to a cookie — you deserve it.

Posted in JavaScript | 1 Comment

Responsible JavaScript

I’m going to kick the new year off with a 10 part series that I call “Responsible JavaScript.”

Most professional JavaScript programmers are well aware of the “bad” parts of JavaScript. We’re told to avoid them at all costs and our programs will be better as a result. For an in-depth overview of the bad parts of JavaScript, check out Doug Crockford’s JavaScript: The Good Parts. In addition to the bad parts, there are piles of other best practices which we’re told to strictly adhere to (no globals, eval is evil, …).

While all of these mantra’s are wise words to live by, it’s important to understand exactly why these best practices exist. Through that understanding, we can even find responsible ways to make use of some of these forbidden areas in our programs.

So without further ado, here is my list of focus points (in no particular order):

  1. Part 1: Globals
  2. Part 2: Namespaces
  3. Part 3: Prototype Modification
  4. Part 4: Using Factories
  5. Part 5: Using ‘this’
  6. Part 6: Incrementing and Decrementing
  7. Part 7: Using Switch
  8. Part 8: Testing Equality
  9. Part 9: Using eval
  10. Part 10: The $ function

Keep checking back here, I’ll be updating these daily. Also, if you’re in NYC, I’ll be presenting on these and a few other areas next week at the Refresh NYC January Meeting.

Posted in JavaScript | 1 Comment