DEV Community

Cover image for Namespaces Quickly Explained
Milecia
Milecia

Posted on • Updated on

Namespaces Quickly Explained

Has anyone ever asked you what a namespace is? I had someone message me about namespaces a little while ago and now seems like a good time to do a quick review. You don't have to have a vague understanding of what that keyword means anymore.

To put it simply, a namespace is just a way to keep names separate from each other. That's why you can use multiple libraries that have the same class names and method names and they don't conflict with each other. All you have to do is specify the namespace you want to use and then you can access the class or method that you need.

Namespaces are a way to give your code context which will help keep the meaning of your code clearer when you come back to it later. A method called Draw() in a Triangle namespace will be completely different from a method called Draw() in an Octagon namespace and that's what you would expect.

One thing to keep in mind is that all of your namespaces should have unique names. No two namespaces should be the same. Since this is a requirement, sometimes those namespace names can get too long to use in your code. That's ok because you can make aliases for your namespaces if you need to.

You can also have completely anonymous namespaces which means you don't give them a name at all. Most of the time you'll only do this when you want to make variable declarations that are invisible to code in other files. That's not something you'll see or use every day, but it's nice to be aware that it's an option.

You can have nested namespaces too. These are a little interesting because the nested namespace has access to all of the parent namespace methods, but the parent namespace has to specifically use the nested namespace to get access to its methods.

As you can see, namespaces aren't that complicated. It's literally a name that holds other names. Hopefully that gives you a little more confidence when you're reading code because not knowing these little things made me feel like a phony at first. Is there anything you can add on about namespaces?


Hey! You should follow me on Twitter because reasons: https://twitter.com/FlippedCoding

Top comments (2)

Collapse
 
jay97 profile image
Jamal Al

Very well written. And u didn't target any language which is even better

Collapse
 
maestromac profile image
Mac Siri

Thats a great explanation I wish I can't across a lot sooner.