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.
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.
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)
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.
just think of it as a logical grouping of objects and functionality
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With