Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a Namespace?

I didn't take the usual CS route to learning programming and I often hear about namespaces but I don't really understand the concept. The descriptions I've found online are usually in the context of C which I'm not familiar with.

I am been doing Ruby for 2 years and I'm trying to get a deeper understanding of the language and OOP.

like image 995
kush Avatar asked Jun 13 '09 16:06

kush


4 Answers

I am going to provide a more commonplace description.

Say my wife has a sister named Sue, and so do I. How can I tell them apart in a conversation? By using their last names ("Sue Larson" vs "Sue Jones"). The last name is the namespace.

This is a limited example of course, and in programming, the potential family members may be far more numerous than my example, therefore the potential for collisions is higher. Namespaces are also hierarchical in some languages (e.g. java), which is not paralleled with last names.

But otherwise it is a similar concept.

like image 141
jwl Avatar answered Nov 20 '22 07:11

jwl


Definition of namespace from Wikipedia:

A namespace is an abstract container or environment created to hold a logical grouping of unique identifiers (i.e., names). ...

For example, one place you can find namespaces usable is something like this:

You define a constant or a variable, or even a class which has a generic name. If you don't wish to rename this constant/variable/class, but need to have another one with the same name, you can define that new instance in different namespace.

In ruby, a module is basically the same thing a namespace is in C++.

eg:

module Foo
  BAZ = 1
end

module Bar
  BAZ = 2
end

puts Foo::BAZ #=> 1
puts Bar::BAZ #=> 2

So, there, you have constant BAZ declared in two modules (aka namespaces in ruby)

like image 39
rasjani Avatar answered Nov 20 '22 07:11

rasjani


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.

like image 15
mikej Avatar answered Nov 20 '22 06:11

mikej


just think of it as a logical grouping of objects and functionality

like image 3
Cody C Avatar answered Nov 20 '22 06:11

Cody C