Skip to main content

Item 28: Partition the global namespace.

Item 28: Partition the global namespace.
The biggest problem with the global scope is that there's only one of them. In a large software project, there is
usually a bevy of people putting names in this singular scope, and invariably this leads to name conflicts. For
example, library1.h might define a number of constants, including the following:
const double LIB_VERSION = 1.204;
Ditto for library2.h:
const int LIB_VERSION = 3;
It doesn't take great insight to see that there is going to be a problem if a program tries to include both library1.h
and library2.h. Unfortunately, outside of cursing under your breath, sending hate mail to the library authors, and
editing the header files until the name conflicts are eliminated, there is little you can do about this kind of
problem.
You can, however, take pity on the poor souls who'll have your libraries foisted on them. You probably already
prepend some hopefully-unique prefix to each of your global symbols, but surely you must admit that the
resulting identifiers are less than pleasing to gaze upon.
A better solution is to use a C++ namespace. Boiled down to its essence, a namespace is just a fancy way of
letting you use the prefixes you know and love without making people look at them all the time. So instead of
this,
const double sdmBOOK_VERSION = 2.0;
class sdmHandle { ... };
sdmHandle& sdmGetHandle();
// in this library,
// each symbol begins
// with "sdm"
// see Item 47 for why you
// might want to declare
// a function like this
you write this:
namespace sdm {
const double BOOK_VERSION = 2.0;
class Handle { ... };
Handle& getHandle();
}
Clients then access symbols in your namespace in any of the usual three ways: by importing all the symbols in a
namespace into a scope, by importing individual symbols into a scope, or by explicitly qualifying a symbol for
one-time use. Here are some examples:
void f1()
{
using namespace sdm;
// make all symbols in sdm
// available w/o qualification
// in this scope
cout << BOOK_VERSION; // okay, resolves to
                     // sdm::BOOK_VERSION
Handle h = getHandle(); // okay, Handle resolves to
                       // sdm::Handle, getHandle
                      // resolves to sdm::getHandle
...
...
}
void f2()
{
using sdm::BOOK_VERSION;
// make only BOOK_VERSION
// available w/o qualification
// in this scope
cout << BOOK_VERSION; // okay, resolves to
                     // sdm::BOOK_VERSION
Handle h = getHandle(); // error! neither Handle
                       // nor getHandle were
                      // imported into this scope
...
...
}
void f3()
{
cout << sdm::BOOK_VERSION;
...
// okay, makes BOOK_VERSION
// available for this one use
// only
double d = BOOK_VERSION; // error! BOOK_VERSION is
                        // not in scope
Handle h = getHandle(); // error! neither Handle
                       // nor getHandle were
                      // imported into this scope
...
}
(Some namespaces have no names. Such unnamed namespaces are used to limit the visibility of the elements
inside the namespace. For details, see Item M31.)
One of the nicest things about namespaces is that potential ambiguity is not an error (see Item 26). As a result,
you can import the same symbol from more than one namespace, yet still live a carefree life (provided you never
actually use the symbol). For instance, if, in addition to namespace sdm, you had need to make use of this
namespace,
namespace AcmeWindowSystem {
...
typedef int Handle;
...
}
you could use both sdm and AcmeWindowSystem without conflict, provided you never referenced the symbol
Handle. If you did refer to it, you'd have to explicitly say which namespace's Handle you wanted:
void f()
{
using namespace sdm;
using namespace AcmeWindowSystem;
// import sdm symbols
// import Acme symbols
...
// freely refer to sdm
// and Acme symbols
// other than Handle
Handle h; // error! which Handle?
sdm::Handle h1; // fine, no ambiguity
AcmeWindowSystem::Handle h2; // also no ambiguity
...
}
Contrast this with the conventional header-file-based approach, where the mere inclusion of both sdm.h and
acme.h would cause compilers to complain about multiple definitions of the symbol Handle.
Namespaces were added to C++ relatively late in the standardization game, so perhaps you think they're not that
important and you can live without them. You can't. You can't, because almost everything in the standard library
(see Item 49) lives inside the namespace std. That may strike you as a minor detail, but it affects you in a very
direct manner: it's why C++ now sports funny-looking extensionless header names like , ,
etc. For details, turn to Item 49.
Because namespaces were introduced comparatively recently, your compilers might not yet support them. If
that's the case, there's still no reason to pollute the global namespace, because you can approximate namespaces
with structs. You do it by creating a struct to hold your global names, then putting your global names inside this
struct as static members:
// definition of a struct emulating a namespace
struct sdm {
static const double BOOK_VERSION;
class Handle { ... };
static Handle& getHandle();
};
const double sdm::BOOK_VERSION = 2.0;
// obligatory defn
// of static data
// member
Now when people want to access your global names, they simply prefix them with the struct name:
void f()
{
cout << sdm::BOOK_VERSION;
...
sdm::Handle h = sdm::getHandle();
...
}
If there are no name conflicts at the global level, clients of your library may find it cumbersome to use the fully
qualified names. Fortunately, there is a way you can let them have their scopes and ignore them, too.
For your type names, provide typedefs that remove the need for explicit scoping. That is, for a type name T in
your namespace-like struct S, provide a (global) typedef such that T is a synonym for S::T:
typedef sdm::Handle Handle;
For each (static) object X in your struct, provide a (global) reference X that is initialized with S::X:
const double& BOOK_VERSION = sdm::BOOK_VERSION;
Frankly, after you've read Item 47, the thought of defining a non-local static object like BOOK_VERSION will
probably make you queasy. (You'll want to replace such objects with the functions described in Item 47.)
Functions are treated much like objects, but even though it's legal to define references to functions, future
maintainers of your code will dislike you a lot less if you employ pointers to functions instead:
sdm::Handle& (* const getHandle)() =
// getHandle is a
sdm::getHandle;
// const pointer (see
// Item 21) to
// sdm::getHandle
Note that getHandle is a const pointer. You don't really want to let clients make it point to something other than
sdm::getHandle, do you?
(If you're dying to know how to define a reference to a function, this should revitalize you:
sdm::Handle& (&getHandle)() =
// getHandle is a reference
sdm::getHandle;
// to sdm::getHandle
Personally, I think this is kind of cool, but there's a reason you've probably never seen this before. Except for
how they're initialized, references to functions and const pointers to functions behave identically, and pointers to
functions are much more readily understood.)
Given these typedefs and references, clients not suffering from global name conflicts can just use the unqualified
type and object names, while clients who do have conflicts can ignore the typedef and reference definitions and
use fully qualified names. It's unlikely that all your clients will want to use the shorthand names, so you should
be sure to put the typedefs and references in a different header file from the one containing your
namespace-emulating struct.
structs are a nice approximation to namespaces, but they're a long trek from the real thing. They fall short in a
variety of ways, one of the most obvious of which is their treatment of operators. Simply put, operators defined
as static member functions of structs can be invoked only through a function call, never via the natural infix
syntax that operators are designed to support:
// define a namespace-emulating struct containing
// types and functions for Widgets. Widget objects
// support addition via operator+
struct widgets {
class Widget { ... };
// see Item 21 for why the return value is const
static const Widget operator+(const Widget& lhs,
const Widget& rhs);
...
};
// attempt to set up global (unqualified) names for
// Widget and operator+ as described above
typedef widgets::Widget Widget;
const Widget (* const operator+)(const Widget&,
const Widget&);
// error!
// operator+
// can't be a
// pointer name
Widget w1, w2, sum;
sum = w1 + w2; // error! no operator+
              // taking Widgets is
             // declared at this
            // scope
sum = widgets::operator+(w1, w2); // legal, but hardly
                                 // "natural" syntax
Such limitations should spur you to adopt real namespaces as soon as your compilers make it practical.

Comments

Popular posts from this blog

CKA Simulator Kubernetes 1.22

  https://killer.sh Pre Setup Once you've gained access to your terminal it might be wise to spend ~1 minute to setup your environment. You could set these: alias k = kubectl                         # will already be pre-configured export do = "--dry-run=client -o yaml"     # k get pod x $do export now = "--force --grace-period 0"   # k delete pod x $now Vim To make vim use 2 spaces for a tab edit ~/.vimrc to contain: set tabstop=2 set expandtab set shiftwidth=2 More setup suggestions are in the tips section .     Question 1 | Contexts Task weight: 1%   You have access to multiple clusters from your main terminal through kubectl contexts. Write all those context names into /opt/course/1/contexts . Next write a command to display the current context into /opt/course/1/context_default_kubectl.sh , the command should use kubectl . Finally write a second command doing the same thing into ...

OWASP Top 10 Threats and Mitigations Exam - Single Select

Last updated 4 Aug 11 Course Title: OWASP Top 10 Threats and Mitigation Exam Questions - Single Select 1) Which of the following consequences is most likely to occur due to an injection attack? Spoofing Cross-site request forgery Denial of service   Correct Insecure direct object references 2) Your application is created using a language that does not support a clear distinction between code and data. Which vulnerability is most likely to occur in your application? Injection   Correct Insecure direct object references Failure to restrict URL access Insufficient transport layer protection 3) Which of the following scenarios is most likely to cause an injection attack? Unvalidated input is embedded in an instruction stream.   Correct Unvalidated input can be distinguished from valid instructions. A Web application does not validate a client’s access to a resource. A Web action performs an operation on behalf of the user without checkin...