« « Learning about teaching at Code With Me

“Is there a Strunk & White for code?” » »

Learning to love…namespacing (advancing code organization)

Posted by on Aug 19, 2012 in Blog | 6 Comments

Before I can settle down to work, I feel the need to clean my apartment. All the dirty dishes go in the dishdrain. The blanket goes behind the couch. Miscellaneous dust is vacuumed. The physical space represents how cluttered my brain feels, so I like to start with it being organized.

What I’m trying to improve on, is that currently I go through this cleanup every Saturday morning. I’d prefer to just…keep it organized to begin with.

So is it with code for me right now. I just rush through, trying to keep information organized into separate pieces, called functions. Then, the day before I meet with one of my “code-reviewers” at my organization, I say, “Oh, no!” and quickly reorganize everything, and fix all my indentation. “Look, it’s organized!” I say.

But recently, one of my mentors suggested pair-programming, a concept where we work together on the code and I realized my fake organization would be found out for what it is. I need to rectify that…NOW.

So, one of my new favorite tools for staying organized as I go, as I work on Big Projects, is called a “namespace.”  Jonathan Stray introduced this concept, but I don’t think I got it until Troy Thibodeaux re-explained. Not a comment on either of them, just that multiple explanations is helpful.

Side note: Having access to Jonathan, Troy (another expert coder, who actually used to work in AP DC, and is one of the smartest, most helpful and calmest people I’ve ever met over the phone, he’s at AP New Orleans) plus several others, from a coding perspective, within my organization, is an amazing opportunity. I feel myself learning even faster, and I just regret not looping Troy into my study sooner.  

Just feel pressured that if their combined force can’t get me where I want to go, I have very big problems. Can’t decide if I’m totally giddy with that kind of knowledge, or totally afraid.  I’ll go with giddy.

Anyway, the idea, if I’m explaining this right, is that you attach all of the blocks of code to execute, or functions, to a giant variable (the namespace), which is attached to the window, which represents the actual webpage, and is always available to your JavaScript.  

You also attach information you need to pass among the functions to that variable. Then, all the functions can access the information, and you don’t have to shove it around inside () as arguments.

Another great feature is you store all of the functions, but by wrapping code in functions, you have greater control over when your code is run, or executed. You’ll see in the example below, I create two functions, but only run them, by adding () after a function name, in the initialize function.

An added bonus is if you inspect this giant object in the Web Developer console, you will see all of your functions and pieces of information as you dig into the object.

I like this strategy a lot, and am trying to approach my projects this way from the start.  I will leave you with an example of short namespaced code.

myAwesomeMap.getColor = function() {
   myAwesomeMap.color = 'tomato';
myAwesomeMap.colorAlabama = function() {
   $('#alabama').css('background-color', myAwesomeMap.color);
myAwesomeMap.initialize = function() {
« « Learning about teaching at Code With Me

“Is there a Strunk & White for code?” » »
  • http://lifeandcode.tumblr.com Lisa Williams

    So is there a Strunk and White for code?  I’m teaching myself, and I know things like my indentation and the like must be all screwed up, but I haven’t really found any reference that would help me out.  Do the conventions vary widely from language to language?


    Michelle Minkoff Reply:

    Please see the newest blog post, “Is there a Strunk & White for Code?”. Too big of a question for the comments section.


  • Pingback: Michelle Minkoff » “Is there a Strunk & White for code?”()

  • http://richardcornish.com/ Rich

    There’s some repetition in your object. It’s not wrong per se, but practicing DRY (“Don’t repeat yourself”) is a good guideline to follow when possible. Here is how I might write it:

    var myAwesomeMap = window.myAwesomeMap || {};myAwesomeMap = {    getColor: function () {        this.color = ‘tomato';    },    colorAlabama: function () {        $(‘#alabama’).css(‘background-color’, this.color);    },    initialize: function () {        this.getColor();        this.colorAlabama();    }};myAwesomeMap.initialize();

    The object name `myAwesomeMap` is used fewer times by using key/value pairs instead of dot notation. It also tends to be more readable. When used in an object, `this` simply refers to the current object, even though `this` is awfully confusing in other contexts. We also do a “best practices” check on the existence of the `myAwesomeMap` variable to make sure we don’t blow it away if it already exists.

    I might also suggest using an Immediately Invoked Function Expression (IIFE) here and with a full example with jQuery included because otherwise the “$” variable is undefined. The `getColor` function is maybe a bit overkill because you’re just asking for the color, which could be more simply defined as `color: tomato,` instead of a `getColor` function. That would also let you cut down on the initialize and run `this.colorAlabama()`.

    Answering Lisa’s comment, there are guidelines (mostly written by Yahoo!’s Douglas Crockford) that are good practices to use with JavaScript. But like writing, there can be times to break rules, be it for creativity, performance, or organization, and like writing you should learn the conventions and best practices first and let loose judiciously later. I’ll post some resources on Michelle’s other post to answer that question.


    Michelle Minkoff Reply:

    Thanks so much, Rich. It may be time to return to Crockford, I really struggled the last time I tried it. I like your key/value structure, started trying it on a new project today, which is going well. To be fair, Troy taught me the “best practices check”, but I left it off here, because I wasn’t clear enough on how it works to explain effectively. Nice notes here, which are contributing to my learning process, and I very much appreciate your comment here and on the other post. Extremely helpful as I push forward. Thank you!


    Rich Reply:

    Crockford’s writing can be dry and pedantic, but the only things I really take away from him are the module design pattern and JSLint to make my code pretty. I don’t necessarily need to know the “why” behind every code design decision; I’d just like a good idea skimming the reasons and then more importantly do it to reap the benefits of well-designed code.

    The truth is that the basic `$(document).ready()` works pretty dang well already because enhancing HTML with jQuery is to simply “get something and do something with it” with the occasional event tossed in. If all you’re doing is enhancing basic markup, you don’t really need to create an object to declutter the global namespace because you’re not making any global variables or global functions as everything is an anonymous getter/setter. If on the other hand, you’re making the next Gmail, then… :)

    It has always been and always will be about purpose of code. You make an election map this year with `$(document).ready()`, fine. But what about next year? Or the primaries? Or tracking an official through offices? As the data sprawls, the code will have to be more organized.

    And you’re welcome! Always glad to share what little I know. I wouldn’t mind reading what you’ve discovered about Raphael, TileMill, or Node.js. :)