Skip to content

Understanding Namespaces by Analogy

2010 June 10
by Tedb0t

Namespaces (or “packages” in Java & ActionScript) are a programming concept that get important when you’re dealing with lots of different libraries and other code-sources.  Consider this analogy:

Every state in the U.S. has zero or one McDonald’s.   If you’re in a state with a McDonald’s, referring to that McDonald’s is easy, you just say “let’s go to McDonald’s” and everyone assumes you mean the one in your state.  But if your state doesn’t have a McDonald’s and you say that, which McDonald’s are you referring to?  Here’s what this looks like in code:

public class NewYork {
    public var mcDonalds;
}
public class NewJersey{
    // no McDonald's here!
}

Now if you’re instantiating objects, it’s a typical situation:

int main(){
    myState = new NewYork();
    neighborState = new NewJersey();

    myMcDs = myState.mcDonalds;
    goTo(myMcDs);
}

But if you’re dealing with static methods or properties of classes from a library, for instance, you’ve got to know the namespace:

namespace NewYork {
    public var mcDonalds;
}

namespace NewJersey {
    //...
}

int main(){
    goTo(NewYork::mcDonalds);
}

Related Posts:

  • No Related Posts


  • http://blog.ygolana.com Peter

    Great analogy! I really like it!
    Recently I started posting interestnig analogies I found on the web on blog.ygolana.com. I thought it could be a good idea to create a place where people can share useful analogies such as yours.

    • http://www.liminastudio.com Tedb0t

      Cool, go for it!