Kennis Keep your global namespace clean

Keep your global namespace clean

A good piece of advice from our JavaScript tech day today: keep your global namespace clean. There is two options to make that happen: 1) good intentions, 2) unit test it.

I have a lot of good intentions, but unit tests seem to work better. Here is the Jasmine code:

describe("General tests", function() {
describe("globals", function() {
it("should expose only a certain amount of variables", function() {
var expectedGlobals = ["util", "KeyCode", "logger", "l", "langur"];
var exposedGlobals = detectGlobals.analyze();
var expectedButNotDetected = _.difference(expectedGlobals, exposedGlobals);
var detectedButNotExpected = _.difference(exposedGlobals, expectedGlobals);
expect(_.size(exposedGlobals)).toEqual(_.size(expectedGlobals));
expect(expectedButNotDetected.length).toEqual(0);
expect(detectedButNotExpected.length).toEqual(0);
});
});
});

Note that you have to run this test at the very end of your testsuite to detect any globals that are created during the execution of the tests.

Go here for the gist with the Javascript that does the actual work (that gist was heavily inspired by this code, credits go to kangax (Juriy Zaytsev) ).