0

One of the greatest offenses in the C++ community is writing using namespace xyz instead of writing the namespace out everywhere in the code.

Ruby has the functional equivalent of namespaces via modules. All of the proposed issues with using an entire namespace in C++ are perfectly valid for including an entire module in Ruby. But in Ruby it is not condemned to do this.

So why doesn't Ruby have the same namespace controvery as C++? What is the difference between including a module in Ruby and using a namspace in C++?

Community
  • 1
  • 1
Mike S
  • 11,329
  • 6
  • 41
  • 76
  • Presumably the contents of a module are well defined, whereas those of a C++ namespace aren't. But there may be a strong cultural component. Maybe in some contexts it doesn't matter as much if the code doesn't do what you think it is doing. – juanchopanza Oct 20 '15 at 15:56
  • Why close vote? What about this question sounds like an opinion? I'm not looking for opinions. I want to know what the difference is. Why does Ruby not have the same problem? – Mike S Oct 20 '15 at 16:02

3 Answers3

3

There is a strong cultural component to this since it is perfectly valid to import an entire namespace... BUT

c++ has Argument Dependent Lookup (ADL) and ruby does not. As a program grows, it becomes more and more likely that an innocent using namespace x will accidentally change the meaning of the entire program, because the compiler happens to find a better match in the x:: namespace for a function that has the same name and similar signature to one in the (for example) y:: namespace.

This is the reason for the caution on this issue.

Richard Hodges
  • 68,278
  • 7
  • 90
  • 142
2

You generally "include" a module when you are mixing-in a functionality from one module into another. There are some parallels between mix-ins and inheritance where you are "absorbing" the functionality of one module/class into the current module/class. Here's a comparison of the two.

However, if you aren't mixing-in functionality, then you would always use the proper namespace qualifier of the module to access its functions.

Community
  • 1
  • 1
Martin Konecny
  • 57,827
  • 19
  • 139
  • 159
  • So if module A includes module B for its own purposes, and then I include module A in my program, then module B would not be included in the scope of my code? Whereas in C++ with namespaces it would be? – Mike S Oct 20 '15 at 16:36
  • It would be included in the scope. You've effectively mixed B into A, so it doesn't change where you access it from. However if you want to access the functions within module A, you would still use the full namespace qualifier: `A.foo()`, `A.bar()` etc. `include` was only to merge/mix B into A. – Martin Konecny Oct 20 '15 at 16:47
0

You normally don't pull everything via an include at top level (the equivalent of using namespace in C++). you "mix" it in where you need functionality from that specific module.

Mircea
  • 10,216
  • 2
  • 30
  • 46