Adding namespace after the fact

S

snorble

Is it better to build code in a namespace from the start? Or is it relatively easy to place it into a namespace after the fact (just put all of the code between the namespace foo { ... })?
 
J

Juha Nieminen

Is it better to build code in a namespace from the start? Or is it
relatively easy to place it into a namespace after the fact (just
put all of the code between the namespace foo { ... })?

When you declare something inside a namespace, such as for example:

namespace Foo
{
void bar();
}

you can then implement that by using the namespace qualifier instead of
having to surround your code with a namespace block. In other words, you
can do this:

void Foo::bar()
{
// implementation here
}

This can be practical, especially if you want to be strict about indenting
(or are using an editor that autoindents), as it reduces the amount of
indentation of your code.
 
Ö

Öö Tiib

Is it better to build code in a namespace from the start? Or is it relatively easy to place it into a namespace after the fact (just put all of the code between the namespace foo { ... })?

Namespaces provide way to systematically qualify the names with
additional context, sub-context etc. Within context then you can write
the code using very short (unqualified) names for things in same
context. There are lot of ways how to import, alias and typedef names
from other contexts to keep everything short to the point within a
context. As result using namespaces systematically from scratch your
code is short and elegant.

When you write without namespaces first (with maybe add them later) then
you can not have names that make sense only within small context (like
"filter", "loader", "access", "range", "logic"). That very likely does
not even compile to use so common names in global namespace. Therefore
you qualify the names immediately somewhat anyway like
"network_service_loader". Later you add namespaces and get abominations
like "device_network::service::network_service_loader". The whole point
of having the namespaces in language was actually lost as result. It
will feel like converting from C to C++ by replacing 'malloc' with 'new'
and 'struct' with 'class' pointlessly.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,043
Latest member
CannalabsCBDReview

Latest Threads

Top