What Are Namespaces

What are namespaces?

Namespacing does for functions and classes what scope does for variables. It allows you to use the same function or class name in different parts of the same program without causing a name collision.

In simple terms, think of a namespace as a person's surname. If there are two people named "John" you can use their surnames to tell them apart.

The Scenario

Suppose you write an application that uses a function named output(). Your output() function takes all of the HTML code on your page and sends it to the user.

Later on your application gets bigger and you want to add new features. You add a library that allows you to generate RSS feeds. This library also uses a function named output() to output the final feed.

When you call output(), how does PHP know whether to use your output() function or the RSS library's output() function? It doesn't. Unless you're using namespaces.

Example

How do we solve having two output() functions? Simple. We stick each output() function in its own namespace.

That would look something like this:

namespace MyProject;

function output() {
# Output HTML page
echo 'HTML!';
}

namespace RSSLibrary;

function output(){
# Output RSS feed
echo 'RSS!';
}

Later when we want to use the different functions, we'd use:

\MyProject\output();
\RSSLibrary\output();

Or we can declare that we're in one of the namespaces and then we can just call that namespace's output():

namespace MyProject;

output(); # Output HTML page
\RSSLibrary\output();

No Namespaces?

If we didn't have namespaces we'd have to (potentially) change a lot of code any time we added a library, or come up with tedious prefixes to make our function names unique. With namespaces, we can avoid the headache of naming collisions when mixing third-party code with our own projects.

What is a Namespace?

A namespace provides a container to hold things like functions, classes and constants as a way to group them together logically and to help avoid conflicts with functions and classes with the same name that have been written by someone else.

In Ruby this is achieved using modules.

What exactly is a namespace and why is it necessary

From cppreference.com:

Namespaces provide a method for preventing name conflicts in large
projects.

Symbols declared inside a namespace block are placed in a named scope
that prevents them from being mistaken for identically-named symbols
in other scopes.

Multiple namespace blocks with the same name are allowed. All
declarations within those blocks are declared in the named scope.

A namespace works to avoid names conflicts, for example the standard library defines sort() but that is a really good name for a sorting function, thanks to namespaces you can define your own sort() because it won't be in the same namespace as the standard one.

The using directive tells the compiler to use that namespace in the current scope so you can do

int f(){
std::cout << "out!" << std::endl;
}

or:

int f(){
using namespace std;
cout << "out!" << endl;
}

it's handy when you're using a lot of things from another namespace.

source: Namespaces - cppreference.com

Why are namespaces used?

For small, self-contained projects, there's not much need for namespaces, and you'd never create a namespace for each object or concept in your code.

Larger projects using libraries benefit from being isolated from names introduced by those libraries, as well as some internal organisation to make readability easier.

Similarly, when creating a library, it's a good idea to put its contents into a namespace so as not to cause headaches and conflicts for your users (as you don't know how large their projects will be, and what names they may want to use themselves).

To use an analogy: if you have three books, you don't bother organising them alphabetically. But, once you have a hundred, you might decide to categorise them on your bookshelf for easier reference and mental health.

And, if you now borrow another twenty books from a friend, you'd probably keep those in a separate pile so they're easier to find when you need to give them back.

So, to some degree, this is a case of… you'll know why you need it, when you need it.

Trying to understand what are namespaces in Java

A package is a named collection of classes (and possibly subpackages). Packages serve to group related classes and define a namespace for the classes they contain. The Java platform includes packages with names that begin with java, javax and etc.

What are namespaces for ? what about usages?

Given that you use the Clojure tag, I suppose that you'll be interested in a Clojure-specific answer:

what is the purpose of namespaces ?

Clojure namespaces, Java packages, Haskell / Python / whatever modules... At a very high level, they're all different names for the same basic mechanism whose primary purpose is to prevent name clashes in non-trivial codebases. Of course, each solution has its own little twists and quirks which make sense in the context of a given language and would not make sense outside of it. The rest of this answer will deal with the twists and quirks specific to Clojure.

A Clojure namespace groups Vars, which are containers holding functions (most often), macro functions (functions used by the compiler to generate macroexpansions of appropriate forms, normally defined with defmacro; actually they are just regular Clojure functions, although there is some magic to the way in which they are registered with the compiler) and occasionally various "global parameters" (say, clojure.core/*in* for standard input), Atoms / Refs etc. The protocol facility introduced in Clojure 1.2 has the nice property that protocols are backed by Vars, as are the individual protocol functions; this is key to the way in which protocols present a solution to the expression problem (which is however probably out of the scope of this answer!).

It stands to reason that namespaces should group Vars which are somehow related. In general, creating a namespace is a quick & cheap operation, so it is perfectly fine (and indeed usual) to use a single namespace in early stages of development, then as independent chunks of functionality emerge, factor those out into their own namespaces, rinse & repeat... Only the things which are part of the public API need to be distributed between namespaces up front (or rather: prior to a stable release), since the fact that function such-and-such resides in namespace so-and-so is of course a part of the API.

and, more important, should they be used as objects in java (things that have data and functions and that try to achieve encapsulation) ? is this idea to far fetched ? :)

Normally, the answer is no. You might get a picture not too far from the truth if you approach them as classes with lots of static methods, no instance methods, no public constructors and often no state (though occasionally there may be some "class data members" in the form of Vars holding Atoms / Refs); but arguably it may be more useful not to try to apply Java-ish metaphors to Clojure idioms and to approach a namespace as a group of functions etc. and not "a class holding a group of functions" or some such thing.

There is an important exception to this general rule: namespaces which include :gen-class in their ns form. These are meant precisely to implement a Java class which may later be instantiated, which might have instance methods and per-instance state etc. Note that :gen-class is an interop feature -- pure Clojure code should generally avoid it.

or should they be used as packages in java ?

They serve some of the same purposes packages were designed to serve (as already mentioned above); the analogy, although it's certainly there, is not that useful, however, just because the things which packages group together (Java classes) are not at all like the things which Clojure namespaces group together (Clojure Vars), the various "access levels" (private / package / public in Java, {:private true} or not in Clojure) work very differently etc.

That being said, one has to remember that there is a certain correspondence between namespaces and packages / classes residing in particular packages. A namespace called foo.bar, when compiled, produces a class called bar in the package foo; this means, in particular, that namespace names should contain at least one dot, as so-called single-segment names apparently lead to classes being put in the "default package", leading to all sorts of weirdness. (E.g. I find it impossible to have VisualVM's profiler notice any functions defined in single-segment namespaces.)

Also, deftype / defrecord-created types do not reside in namespaces. A (defrecord Foo [...] ...) form in the file where namespace foo.bar is defined creates a class called Foo in the package foo.bar. To use the type Foo from another namespace, one would have to :import the class Foo from the foo.bar package -- :use / :require would not work, since they pull in Vars from namespaces, which records / types are not.

So, in this particular case, there is a certain correspondence between namespaces and packages which Clojure programmers who wish to take advantage of some of the newer language features need to be aware of. Some find that this gives an "interop flavour" to features which are not otherwise considered to belong in the realm of interop (defrecord / deftype / defprotocol are a good abstraction mechanism even if we forget about their role in achieving platform speed on the JVM) and it is certainly possible that in some future version of Clojure this flavour might be done away with, so that the namespace name / package name correspondence for deftype & Co. can be treated as an implementation detail.

or should they be used more generally as a module system or something ?

They are a module system and this is indeed how they should be used.

What is namespace used for, in C++?

Namespace is used to prevent name conflicts.

For example:

namespace foo {
class bar {
//define it
};
}

namespace baz {
class bar {
// define it
};
}

You now have two classes name bar, that are completely different and separate thanks to the namespacing.

The "using namespace" you show is so that you don't have to specify the namespace to use classes within that namespace. ie std::string becomes string.

What is the point in NameSpaces?

It would be obvious if you had to use two libraries with the same class names in the same project (yes, this may happen). With namespaces you can create alias for one of them, and use both without thouching library's core.

What are user-controlled namespaces?

User-controlled namespaces means namespaces where a user, programming in Python, controls what names exist and what values they have. In other words, basically user-created APIs. What it means is that you shouldn't design an API that relies on new __doubleunderscore_names__ that you make up.

"Namespace" here does not refer to the naming convention but to the actual programming scope. For instance, each function has a local namespace for its local variables; a module has a global namespace for its global variables; etc. Users absolutely will use these namespaces -- you will create your own variables, classes, functions, etc.. What it's saying is that you shouldn't make up new magic-looking names and put them in your namespaces.



Related Topics



Leave a reply



Submit