Object-Oriented Programming

Namespaces

Michael L. Collard, Ph.D.

Department of Computer Science, The University of Akron

Name Collisions

  • name collision is when we have the same name for two different things
  • For variables, this occurs when the names are the same
  • With functions/methods, this occurs when the mangled names are the same
  • Sometimes, scope removes these
  • Sometimes, it doesn't, which can be worse as we are using the wrong value

Name Collision Avoidance: Common Prefix

  • Name of the project/company/utility is used in the first part of the name
  • More common with under_score rather than camelCase styles
  • Typically, a C-library or language without function/method overloading
  • A violation of the Method Naming Standard: Prefix/Suffix

Namespaces

  • Common language mechanism to group, and name, sets of functions, classes, constants, and variables
  • Similar to pre-Object-Oriented modules
  • Often referred to in other languages as packages
  • In C++, the keyword namespace is followed by a name followed by a block
  • Does not end in a semicolon (as a class does)
  • :: is the C++ scope resolution operator
  • Can be used to refer to things in a namespace when used with a prefix
  • Can refer to an item in global scope anywhere in the program

Namespaces are Cumulative

  • Can add to them in multiple parts
  • Public part in the include file, private part in the implementation file
  • Collective namespace declared in many files, e.g., std::

using declarations

  • Use in limited situations
  • Never use in an include file

using directives

  • Use in very specific situations
  • Required for std::string literals and std::string_view literals
  • Never use in an include file

using directives

  • Potentially brings all symbols in std into the global namespace
  • Potentially brings all symbols in boost into the global namespace
  • Name collisions with each other, potential name collisions with your code, potential name collisions of any include file you use, directly or indirectly

namespace alias

  • For multiple prefixes, can alias a namespace to reduce the number of prefixes
  • Also can allow for more flexible code
  • Unlike using directives, it still has a documentary purpose
  • Use whenever it makes sense, but don't overuse

Conclusion

  • Any set of functions or variables with an include file should be in a namespace
  • Scalability and preparation for the future demand it
  • Easy to do
  • Self-documents the code