Anonymous namespaces: Are they really that great? - c++

I have been using the static keyword a long time for defining internal linkage. Later, I switched to the C++ style of wrapping local things in anonymous namespaces.
However, now when I have worked with anonymous namespaces for some years, I start to think that static keyword is a lot easier to work with!
A common problem is that I have this pattern:
namespace {
// ...five pages of code...
} // namespace
To see if a certain function has internal or external linkage, I now have to scroll a lot, as opposed to the old C style where I could just check if the function/object had static in front of it.
I know there are things anonymous namespaces do that static can't - hide typedefs - but personally I'm not really very interested in that, anyway.
What are your take on this? Is the win of anonymous namespaces that great that it warrants the decreased readability? Or am I all out wrong?

If the code in your namespace is too long, there's nothing to stop you doing this:
namespace {
int foo(char* x) {
return x[0] + x[1];
}
}
namespace {
int bar(char *x, char *y) {
return foo(x) + foo(y);
}
}
In C++03 the practical advantage of using an unnamed namespace is precisely that the contents have external linkage, (but are still invisible outside the TU because there's no way to refer to them). Template parameters can't have internal linkage:
namespace {
int foo(const char* x) {
return x[0] + x[1];
}
}
static int foo2(const char *x) {
return x[0] + x[1];
}
template <int (*F)(const char*)>
void baz(const char *p) {
F(p);
}
int main() {
baz<foo>("ab"); // OK
baz<foo2>("ab"); // not valid
}

Apart from the very valid points noted by Steve I see other very important aspects in anonymous namespaces that make them superior to static functions:
Locality, ease of refactoring and information hiding.
Assume you have one or two class function that require several other helper functions which are quite specific but do not use class members. If you stick with Robert C. Martin (Functions should be small and serve one well defined purpose) you will often find that large functions can be refactored into smaller ones although these smaller ones might in the beginning only be used in the former big function.
So what Options do you have:
Make a new (perhaps private) class immediately:
This entails quite a lot of typing might be overkill and -lets face it- everybody
is sometimes lazy or in a hurry.
Generate private static functions or non-member functions:
Both entails editing the header file and the cpp file if you do it
properly, so still a little burden that might interrupt your
workflow more than necessary and generates code that unnecessarily
clutters your header file, might necessitate forward declarations or
even additional includes in your header.
Anonymous namespace:
You have a helper function that does not need
member access and serves one purpose -> Put it there and write this
function close to the class methods where it will be used. This is by large
my preferred one:It's quick and it does not clutter the header file.
The namespace clearly states: this is not used by anything else than this cpp. No
friend will use it and no library user will ever know it's existence. You
can hardly be more obvious and often this paradigm will lead to
cleaner function design which is few input parameters and only one
output modified. Further you have function locality: Define just before primary
use. While this might be a drawback I find it quite help ful when browsing the
implementations of large classes. Another advantage is constants that span several
functions but are not really interesting for a library user. Put them in the
namespace as well, best in the same with the functions that use them. If it turns
out later that you need the constants and the functions elsewhere, transform the
whole into a class, its already neatly packed.
Disclaimer: Many people might argue that the use of a pimpl is by far cleaner. This is just my personal opinion.

An anonymous namespace is the only thing that does not let a class declaration pollute the global scope. Very useful when defining a class in a .cpp file.

Related

Is it bad practice to have a class that requires no objects to be created? [duplicate]

Let's say I have, or am going to write, a set of related functions. Let's say they're math-related. Organizationally, should I:
Write these functions and put them in my MyMath namespace and refer to them via MyMath::XYZ()
Create a class called MyMath and make these methods static and refer to the similarly MyMath::XYZ()
Why would I choose one over the other as a means of organizing my software?
By default, use namespaced functions.
Classes are to build objects, not to replace namespaces.
In Object Oriented code
Scott Meyers wrote a whole Item for his Effective C++ book on this topic, "Prefer non-member non-friend functions to member functions". I found an online reference to this principle in an article from Herb Sutter: http://www.gotw.ca/gotw/084.htm
The important thing to know is that: In C++, functions that are in the same namespace as a class is, and that have that class as a parameter, belong to that class' interface (because ADL will search those functions when resolving function calls).
For example:
let's say you have a namespace N
let's say you have a class C, declared in namespace N (in other words, its full name is N::C)
let's say you have a function F, declared in namespace N (in other words, its full name is N::F)
let's say that function F has, among its parameters, a parameter of type C
... Then N::F is part of N::C's public interface.
Namespaced functions, unless declared "friend," have no access to the class's internals, whereas static methods have the right to access the class's internals.
This means, for example, that when maintaining your class, if you need to change your class' internals, you will need to search for side effects in all its methods, including the static ones.
Extension I
Adding code to a class' interface.
In C#, you can add methods to a class even if you have no access to it. But in C++, this is impossible.
But, still in C++, you can still add a namespaced function, even to a class someone wrote for you.
See from the other side, this is important when designing your code, because by putting your functions in a namespace, you will authorize your users to increase/complete the class' interface.
Extension II
A side-effect of the previous point, it is impossible to declare static methods in multiple headers. Every method must be declared in the same class.
For namespaces, functions from the same namespace can be declared in multiple headers (the almost-standard swap function is the best example of that).
Extension III
The basic coolness of a namespace is that in some code, you can avoid mentioning it, if you use the keyword using:
#include <string>
#include <vector>
// Etc.
{
using namespace std ;
// Now, everything from std is accessible without qualification
string s ; // Ok
vector v ; // Ok
}
string ss ; // COMPILATION ERROR
vector vv ; // COMPILATION ERROR
And you can even limit the "pollution" to one class:
#include <string>
#include <vector>
{
using std::string ;
string s ; // Ok
vector v ; // COMPILATION ERROR
}
string ss ; // COMPILATION ERROR
vector vv ; // COMPILATION ERROR
This "pattern" is mandatory for the proper use of the almost-standard swap idiom.
And this is impossible to do with static methods in classes.
So, C++ namespaces have their own semantics.
But it goes further, as you can combine namespaces in a way similar to inheritance.
For example, if you have a namespace A with a function AAA, a namespace B with a function BBB, you can declare a namespace C, and bring AAA and BBB in this namespace with the keyword using.
You can even bring the full content of a namespace inside another, with using namespace, as shown with namespace D!
namespace A
{
void AAA();
void AAA2();
}
namespace B
{
void BBB();
}
namespace C
{
using A::AAA;
using B::BBB;
}
namespace D
{
using namespace A;
using namespace B;
}
void foo()
{
C::AAA();
// C::AAA2(); // ERROR, won't compile
C::BBB();
}
void bar()
{
D::AAA();
D::AAA2();
D::BBB();
}
Conclusion
Namespaces are for namespaces.
Classes are for classes.
C++ was designed so each concept is different, and is used differently, in different cases, as a solution to different problems.
Don't use classes when you need namespaces.
And in your case, you need namespaces.
There are a lot of people who would disagree with me, but this is how I see it:
A class is essentially a definition of a certain kind of object. Static methods should define operations that are intimately tied to that object definition.
If you are just going to have a group of related functions not associated with an underlying object or definition of a kind of object, then I would say go with a namespace only. Just for me, conceptually, this is a lot more sensible.
For instance, in your case, ask yourself, "What is a MyMath?" If MyMath does not define a kind of object, then I would say: don't make it a class.
But like I said, I know there are plenty of folks who would (even vehemently) disagree with me on this (in particular, Java and C# developers).
If you need static data, use static methods.
If they're template functions and you'd like to be able to specify a set of template parameters for all functions together then use static methods in a template class.
Otherwise, use namespaced functions.
In response to the comments: yes, static methods and static data tend to be over-used. That's why I offered only two, related scenarios where I think they can be helpful. In the OP's specific example (a set of math routines), if he wanted the ability to specify parameters - say, a core data type and output precision - that would be applied to all routines, he might do something like:
template<typename T, int decimalPlaces>
class MyMath
{
// routines operate on datatype T, preserving at least decimalPlaces precision
};
// math routines for manufacturing calculations
typedef MyMath<double, 4> CAMMath;
// math routines for on-screen displays
typedef MyMath<float, 2> PreviewMath;
If you don't need that, then by all means use a namespace.
You should use a namespace, because a namespace has the many advantages over a class:
You don't have to define everything in the same header
You don't need to expose all your implementation in the header
You can't using a class member; you can using a namespace member
You can't using class, though using namespace is not all that often a good idea
Using a class implies that there is some object to be created when there really is none
Static members are, in my opinion, very very overused. They aren't a real necessity in most cases. Static members functions are probably better off as file-scope functions, and static data members are just global objects with a better, undeserved reputation.
I would prefer namespaces, that way you can have private data in an anonymous namespace in the implementation file (so it doesn't have to show up in the header at all as opposed to private members). Another benefit is that by using your namespace the clients of the methods can opt out of specifying MyMath::
I want to summarize and add to other answers. Also, my perspective is in the world of header-only.
Namespaces
Pros:
simple solution for naming hierarchies
they carry no semantics, so it is simpler to read
can live in different files (headers)
can be extended
ADL
shortcut can be defined (using).
Plays well with operator overload
Can be used for branding (you can design your code and put a namespace over it without much though)
Cons:
everything is public
private things need unnamed namespace so it is not explicit
ADL (yes, some people despise ADL)
can be extended (this can be a bad thing, specially in combination with ADL, semantics of existing code can change by extending the namespace)
functions need to be defined (or declared) in order of use
Classes with static methods
Pros:
can have private components (function, variables) and they are explicitly marked.
classes can be friended
can be type-parametrized (templates)
can be template parameters themselves
can be instantiated
can be passed to functions (static functions behave like non-static method by default).
it is easier to find patterns and go from groups of independent functions and convert them to a proper class (eventually with non static members)
dependencies among classes is well defined
functions (the static method) can be defined in any order
Cons:
No ADL
cannot be extended
needs the keyword static everywhere (opportunity to make fun of the language)
an overkill to solve the naming problem alone. Difficult to read in that case.
the functions (static methods) always need qualification (myclassspace::fun). There is no way to declare shortcuts (using).
almost useless for operator overload, needs complicated friend mechanism for that.
can not be used for branding.
you need to remember end it with ; :)
In summary, classes with static methods are better units of code and allow more meta programming, and except for ADL and some syntactic quirks, can replicate all the features of namespaces, but they can be an overkill sometimes.
Companies, such as Bloomberg, prefer classes over namespaces.
If you don’t like ADL or operator overload, classes with static methods is the way to go.
IMO, it would be nice if namespace and classes are integrated to become two sides of the same coin.
For example identify a namespace in the language as a class were the methods are static by default.
And then be able to use them as template parameters.
I wouldn't be sure what to do with ADL (may be it could be restricted to symbolic operators functions alone, e.g. operatorX, which was the original motivation for operator overload and ADL in the first place)
Why would I choose one over the other as a means of organizing my software?
If you use namespaces, you will frequently hit a language defect that functions which call each other must be listed in a specific order, because C++ can't see definitions further down in the file.
If you use classes, this defect does not occur.
It can be easier and cleaner to wrap implementation functions in a class than to maintain declarations for them all or put them in an unnatural order to make it compile.
One more reason to use class - Option to make use of access specifiers. You can then possibly break your public static method into smaller private methods. Public method can call multiple private methods.
Both namespace and class method have their uses. Namespace have the ability to be spread across files however that is a weakness if you need to enforce all related code to go in one file. As mentioned above class also allows you to create private static members in the class. You can have it in the anonymous namespace of the implementation file however it is still a bigger scope than having them inside the class.

c++17 namespaces, is it possible to force qualified access ALWAYS?

to my surprise, when a function is declared in the same namespace as a variable, the function may access that variable without qualification.
// file qqq.cpp
namespace aaa {
void f();
int x;
}
void aaa::f() {
aaa::x; // 0. INTENDED ACCESS to x in namespace aaa (also works)
x; // 1. SURPRISE: x can be accessed without aaa:: qualification
bool x; // 2. SURPRISE: given (1) why is it allowed to redefine x?
}
question:
A) is there any way to ensure that all objects in a namespace be blind to its fellow constituents, and to require access always through :: ?
B) if not, what would be the correct coding practice to obtain the desired behavior?
C) if not, an alternative solution would be to separate the each namespace into 2, one for functions and another for variables, like f_aaa and v_aaa. but this seems quite clunky and ugly in practical use, eg. void f_sqlite::myfun() { v_sqlite::myvar; } instead of just void sqlite::myfun() { sqlite::myvar; }
edit 1: context, the "problem" im trying to solve:
refactoring several thousand lines of code, namespaces was thought to be suitable for bundling related elements, eg. an "sqlite" namespace for sqlite utility functions and variables used throughout the code base. forced access through :: would be an excellent way of increasing clarity and avoiding name clashes and hiding. separate namespaces for "one bundle" would defeat the purpose. classes would not seem conceptually appropriate.
edit 2:
D) is it possible to get a WARNING (enable compiler flag) to signal when a function in namespace aaa accesses a variable in namespace aaa without qualification?
edit 3:
i think i will end up using "separate namespaces" anyway, but by way of nested namespaces
// file qqq.cpp
namespace aaa::f { // namespace for functions
void f();
void g();
}
namespace aaa::v { // namespace for variables
int x;
}
// definition of function f inside namespace aaa::f
void aaa::f::f() {
aaa::v::x; // only way of accessing x in aaa::v (good) (ugly)
x; // compiler error (good)
bool x; // normal scope hiding (good)
g(); // works: ARGH! would like to force qualifying with aaa::f::
}
still rather ugly though. and! functions can still call each other unqualified, objects can still call/reference each other unaqulified. would really have been nice to simply be able to put some "force-qualifier" (like "private") on all or some element inside a namespace.
A) is there any way to prevent all objects in a namespace to be blind to its fellow constituents, and to require access always through :: ?
There isn't.
B) if not, what would be the correct coding practice to obtain the desired behavior?
Use a class.
C) if not, an alternative solution would be to separate the aaa namespace into 2, one for functions and another for variables, like f_aaa and v_aaa. but this seems quite clunky and ugly in practical use, eg. void f_sqlite::myfun() { v_sqlite::myvar; } instead of just void sqlite::myfun() { sqlite::myvar; }
Use a class to group relevant functions and data together. What You want to hide put in a private section.
Using a separate (nested) namespace for function and variable is not a good idea. It make the code less readable.
Also always qualifying all names is overkill. If the function f is in namespace aaa then it should really prefer variables from that namespace.
And finally the only reason why you would have such problem is because you are using too much global variables (or long functions) which is really a bad practice because it make the code harder to maintain.
So I recommend you to use to use good coding practices like
small functions (less than a screen)
avoid global variables
object-oriented design using class with member functions and data when appropriate.
small files (so you don't get irrelevant stuff)
avoid variables in header files
include only the files you really need (thus you won't get many conflicts if any)
In fact, if you really have the issue you have, it is because current code is large and don't follow good practices..
Other workarounds in comments and answers might works but better to validate if your design is adequate and refactor your code as appropriate.
Extra points:
Another thing that might cause lot of ambiguities is to use basic data type when you should really use custom types.
Uses typed enumeration (enum class) when you want to use some constant for specific parameter instead of define or integers.
Uses class or struct if you have data that are bundled together and are used all over the application.
If you use template functions, you might want to carefully consider what kind of data it would allows particularly if you have a common name like open for the function.

Why define constants in a class versus a namespace? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Static members class vs. normal c-like interface
I am looking at somebodies code and there are several dozen constants defined in a class like this:
// header file
class Defines
{
public:
static const int Val1;
static const int ValN;
static const char* String1;
static const char* StringN;
...
}
// .CPP
const char* Defines::String1 = "some value"
etc.
Is there some reason to do things this was as opposed to using a namespace instead?
Are there advantages/disadvantages of one over the other
--------- Edit ----------
I'm sorry, I obviously should have pointed this out explicitly, as nobody has inferred it from the name of the class - which is "Defines". i.e. these constants are not associated with a particular class, there has been a class created specifically just to hold constants and nothing else, that is all the class Defines contains.
My question is not why should you place constants in a particular class, the question is is there any value in collecting dozens of them together and placing them in a class whose only purpose is to collect together constants, as opposed to collecting them together in a namespace, or just collecting them together in a header file specifically for that purpose etc.
(There is no currently existing namespace in the project therefore potential issues of polluting the namespace as mentioned in answers are not relevant in this case.)
----- 32nd edit -----------
and a follow up question ---
is placing
const char* Defines::StringN = "Somevalue"
in the .h file inefficient versus placing it in the .cpp file?
Because those constants may be tightly coupled to that class. IE Maybe members of the class take those constants as arguments or return them. Maybe the only place they are meaningful is in the interface to this class, so putting them in a separate namespace doesn't make sense because they only matter to that class.
There is no reason to do it the way it is done here; just like there is not really a reason to use class Defines { public: ... }; instead of struct Defines { ... };. Perhaps whoever wrote the code had previously been writing in a language that does not support namespaces/global variables in namespaces, or thought that this looked `neater' than a lot of extern statements and a namespace.
There is some practical use for this, however, if you intend to make some of these constants private, and then give access to only a few functions/classes. From the looks of it, however, this isn't the case, and it would make sense to change this to be a namespace -- that way, one could use using Defines::constant; and similar.
Response to first edit: The global namespace is also a namespace, and it is more dangerous to pollute than other namespaces, as things are more likely to leak into it. In that sense, it is better to put the variables in a class, but still not as good as putting them in a namespace of their own.
Response to second edit: const char* Defines::StringN = "Somevalue"; in a header would lead to the constant being defined multiple times, and the program would fail to link. However, if you prepend an extern to that, and put the definition in a .cpp file, everything will be fine, and there should be no performance penalty.
For a few reasons:
You're not cluttering your namespace with potentially random constants.
You're adding meaning to both the class and the constants themselves by including them with their associated class.
If I were to define a global/namespace constant named NAME, then what is it associated with? If I added into the class itself, then you're forced to reference is with the class name, which adds meaning to the usage and makes the code more readable and less error prone.
Of course, this can be abused. You can misplace constants. You can improperly put truly global constants in specific classes. You can, in both cases, give bad names.
In general, there's no reason to use a type this way. I have seen it argued that if the "collection of constants" evolves into a concrete object, starting this way makes the transition easier. In practice, I've never seen this happen. It just hides intent, and potentially flutters the code with private constructors.
One could argue that classes work with templates, while namespaces do not. So something like the following would only work if Defines is a class:
template<typename T> int function() {
return T::x + T::y;
}
//later
cout << function<Defines>() << function<OtherDefines>() << endl;
In most cases, there's probably a redesign that would work better, particularly if all you have are "constants" that aren't really. Occasionally, this may come in handy, though.
At times, it can also fight argument dependent lookup. In brief, the compiler is allowed to expand it's search for eligable function names to different name namespaces based on the parameters passed to the function. This does not extend to static functions of a class. This applies more to the general case, though, where the "static class" also includes nested types and functions in addition to the collection of constants.
Why people do this varies. Some come from languages where can't be used this way, others just don't know any better.
For most things, it makes sense to give them the smallest scope possible. In this case its not so much an issue of visibility, but in clarity.
If you see String1 in a method, you have no idea where it came from. If you see Defines::String1, you can say "OK, this is a variable from the class Defines, let me go there and see what it is and what it's supposed to be". Looking in one class is a lot better than looking through an entire namespace that might even be spread across multiple source files. Obviously if the variable is in a class because its used primarily in that class, there's no doubt whatsoever that's that's where it should be. :D

Named namespace in implementation file to group const string literals - Good/Bad?

I've grouped several message strings into a named (non anonymous) namespace in the .cpp file for a class handling output as seen in the code below:
namespace Messages
{
static const std::string AppTitle = "The Widgetizer - Serving all your Widget needs";
static const std::string SuccessMsg = "Great success! Widgets for all! ";
static const std::string FailMsg = "No widgets for you!";
};
void Display::printTitle()
{
out << Messages::AppTitle << std::endl;
}
void Display::printSuccessMsg()
{
out << Messages::SuccessMsg << std::endl;
}
void Display::printFailMsg()
{
out << Messages::FailMsg << std::endl;
}
My logic being that this way they're all in one central location, under a namespace with a meaningful and self-documenting name, and they're not exposed to the client code (as they would be if I had put the namespace in the .h file).
Is this a good practice generally or are there pitfalls to this that I'm not seeing?
Is the static keyword necessary if they're in a file scope namespace like this?
In terms of best practices and accepted C++ idiom & style, would this be better off just as an anonymous namespace? Or simply as static const class members?
I admit it's probably overkill for the small program I'm writing since they'll probably only be used in these functions but generally speaking not hard coding message strings is a good habit no?
It's okay I guess, you won't lose any points for this. I don't care much for the term "best practice", it is not a common practice. A lot of programs are written with localization in mind, there's several billion potential customers that don't understand a word of English. No standard C++ solution for that, just common practices on your platform. Like string resources.
Is this a good practice generally or are there pitfalls to this that I'm not seeing?
Grouping related objects in a namespace is good practice if it makes the code clearer; there aren't any particular pitfalls, but deeply nested namespaces can lead to excessively verbose code if you're not careful.
Is the static keyword necessary if they're in a file scope namespace like this?
You need either static or const to give them internal linkage, but it might be better to enclose your namespace in an unnamed namespace instead. Using static at namespace scope is deprecated, and just using const means you'll get a surprise if someone declares extern objects with the same names.
In terms of best practices and accepted C++ idiom & style, would this be better off just as an anonymous namespace? Or simply as static const class members?
If grouping them in a named namespace makes the code more expressive, then do it; otherwise, don't. I'd prefer not to make them class members unless necessary, to avoid adding unnecessary declarations to the header file.
Is this a good practice generally or
are there pitfalls to this that I'm
not seeing?
It don't seem to be any problem with using namespace to do this.
I often see that putting constant values and global configuration variables in namespace (might they be accessed outside of the definition cpp or not) is a good practice. That way you don't have to create a class just for grouping and you still have the name encapsulation working nice.
Is the static keyword necessary if
they're in a file scope namespace like
this?
It's not necessary.
In terms of best practices and accepted C++ idiom & style, would this be better off just as an anonymous namespace? Or simply as static const class members?
Static class member would be overkill and non-sense. If you don't need an instance, don't write a class.
Anonymous namespace would be useful only if the code is limited to a specific CPP file.
I admit it's probably overkill for the small program I'm writing since they'll probably only be used in these functions but generally speaking not hard coding message strings is a good habit no?
Following the DRY principle, it looks like you've done well, even for a small program and even if you think your constants will be used only once. Because in the end you never know what the future is made of.
This is okay if you desire the clarity.
My preference would generally be either:
To define file level static variables without the name space (these are always near the top of the file for me).
To define an anonymous namespace and use non-static variables.
Put the definitions in a private part of my subsystem in their own file, complete with header file.
In a particular case that I did use the method you describe it was a mistake. I had fairly large file 3000+ lines with a number of internal classes. In retrospect I should have put my scoped classes into separate files in the internal part of my subsystem.
Generally I prefer 1 or 2 for simple things and 3 for complicated/large things.

Namespace + functions versus static methods on a class

Let's say I have, or am going to write, a set of related functions. Let's say they're math-related. Organizationally, should I:
Write these functions and put them in my MyMath namespace and refer to them via MyMath::XYZ()
Create a class called MyMath and make these methods static and refer to the similarly MyMath::XYZ()
Why would I choose one over the other as a means of organizing my software?
By default, use namespaced functions.
Classes are to build objects, not to replace namespaces.
In Object Oriented code
Scott Meyers wrote a whole Item for his Effective C++ book on this topic, "Prefer non-member non-friend functions to member functions". I found an online reference to this principle in an article from Herb Sutter: http://www.gotw.ca/gotw/084.htm
The important thing to know is that: In C++, functions that are in the same namespace as a class is, and that have that class as a parameter, belong to that class' interface (because ADL will search those functions when resolving function calls).
For example:
let's say you have a namespace N
let's say you have a class C, declared in namespace N (in other words, its full name is N::C)
let's say you have a function F, declared in namespace N (in other words, its full name is N::F)
let's say that function F has, among its parameters, a parameter of type C
... Then N::F is part of N::C's public interface.
Namespaced functions, unless declared "friend," have no access to the class's internals, whereas static methods have the right to access the class's internals.
This means, for example, that when maintaining your class, if you need to change your class' internals, you will need to search for side effects in all its methods, including the static ones.
Extension I
Adding code to a class' interface.
In C#, you can add methods to a class even if you have no access to it. But in C++, this is impossible.
But, still in C++, you can still add a namespaced function, even to a class someone wrote for you.
See from the other side, this is important when designing your code, because by putting your functions in a namespace, you will authorize your users to increase/complete the class' interface.
Extension II
A side-effect of the previous point, it is impossible to declare static methods in multiple headers. Every method must be declared in the same class.
For namespaces, functions from the same namespace can be declared in multiple headers (the almost-standard swap function is the best example of that).
Extension III
The basic coolness of a namespace is that in some code, you can avoid mentioning it, if you use the keyword using:
#include <string>
#include <vector>
// Etc.
{
using namespace std ;
// Now, everything from std is accessible without qualification
string s ; // Ok
vector v ; // Ok
}
string ss ; // COMPILATION ERROR
vector vv ; // COMPILATION ERROR
And you can even limit the "pollution" to one class:
#include <string>
#include <vector>
{
using std::string ;
string s ; // Ok
vector v ; // COMPILATION ERROR
}
string ss ; // COMPILATION ERROR
vector vv ; // COMPILATION ERROR
This "pattern" is mandatory for the proper use of the almost-standard swap idiom.
And this is impossible to do with static methods in classes.
So, C++ namespaces have their own semantics.
But it goes further, as you can combine namespaces in a way similar to inheritance.
For example, if you have a namespace A with a function AAA, a namespace B with a function BBB, you can declare a namespace C, and bring AAA and BBB in this namespace with the keyword using.
You can even bring the full content of a namespace inside another, with using namespace, as shown with namespace D!
namespace A
{
void AAA();
void AAA2();
}
namespace B
{
void BBB();
}
namespace C
{
using A::AAA;
using B::BBB;
}
namespace D
{
using namespace A;
using namespace B;
}
void foo()
{
C::AAA();
// C::AAA2(); // ERROR, won't compile
C::BBB();
}
void bar()
{
D::AAA();
D::AAA2();
D::BBB();
}
Conclusion
Namespaces are for namespaces.
Classes are for classes.
C++ was designed so each concept is different, and is used differently, in different cases, as a solution to different problems.
Don't use classes when you need namespaces.
And in your case, you need namespaces.
There are a lot of people who would disagree with me, but this is how I see it:
A class is essentially a definition of a certain kind of object. Static methods should define operations that are intimately tied to that object definition.
If you are just going to have a group of related functions not associated with an underlying object or definition of a kind of object, then I would say go with a namespace only. Just for me, conceptually, this is a lot more sensible.
For instance, in your case, ask yourself, "What is a MyMath?" If MyMath does not define a kind of object, then I would say: don't make it a class.
But like I said, I know there are plenty of folks who would (even vehemently) disagree with me on this (in particular, Java and C# developers).
If you need static data, use static methods.
If they're template functions and you'd like to be able to specify a set of template parameters for all functions together then use static methods in a template class.
Otherwise, use namespaced functions.
In response to the comments: yes, static methods and static data tend to be over-used. That's why I offered only two, related scenarios where I think they can be helpful. In the OP's specific example (a set of math routines), if he wanted the ability to specify parameters - say, a core data type and output precision - that would be applied to all routines, he might do something like:
template<typename T, int decimalPlaces>
class MyMath
{
// routines operate on datatype T, preserving at least decimalPlaces precision
};
// math routines for manufacturing calculations
typedef MyMath<double, 4> CAMMath;
// math routines for on-screen displays
typedef MyMath<float, 2> PreviewMath;
If you don't need that, then by all means use a namespace.
You should use a namespace, because a namespace has the many advantages over a class:
You don't have to define everything in the same header
You don't need to expose all your implementation in the header
You can't using a class member; you can using a namespace member
You can't using class, though using namespace is not all that often a good idea
Using a class implies that there is some object to be created when there really is none
Static members are, in my opinion, very very overused. They aren't a real necessity in most cases. Static members functions are probably better off as file-scope functions, and static data members are just global objects with a better, undeserved reputation.
I want to summarize and add to other answers. Also, my perspective is in the world of header-only.
Namespaces
Pros:
simple solution for naming hierarchies
they carry no semantics, so it is simpler to read
can live in different files (headers)
can be extended
ADL
shortcut can be defined (using).
Plays well with operator overload
Can be used for branding (you can design your code and put a namespace over it without much though)
Cons:
everything is public
private things need unnamed namespace so it is not explicit
ADL (yes, some people despise ADL)
can be extended (this can be a bad thing, specially in combination with ADL, semantics of existing code can change by extending the namespace)
functions need to be defined (or declared) in order of use
Classes with static methods
Pros:
can have private components (function, variables) and they are explicitly marked.
classes can be friended
can be type-parametrized (templates)
can be template parameters themselves
can be instantiated
can be passed to functions (static functions behave like non-static method by default).
it is easier to find patterns and go from groups of independent functions and convert them to a proper class (eventually with non static members)
dependencies among classes is well defined
functions (the static method) can be defined in any order
Cons:
No ADL
cannot be extended
needs the keyword static everywhere (opportunity to make fun of the language)
an overkill to solve the naming problem alone. Difficult to read in that case.
the functions (static methods) always need qualification (myclassspace::fun). There is no way to declare shortcuts (using).
almost useless for operator overload, needs complicated friend mechanism for that.
can not be used for branding.
you need to remember end it with ; :)
In summary, classes with static methods are better units of code and allow more meta programming, and except for ADL and some syntactic quirks, can replicate all the features of namespaces, but they can be an overkill sometimes.
Companies, such as Bloomberg, prefer classes over namespaces.
If you don’t like ADL or operator overload, classes with static methods is the way to go.
IMO, it would be nice if namespace and classes are integrated to become two sides of the same coin.
For example identify a namespace in the language as a class were the methods are static by default.
And then be able to use them as template parameters.
I wouldn't be sure what to do with ADL (may be it could be restricted to symbolic operators functions alone, e.g. operatorX, which was the original motivation for operator overload and ADL in the first place)
I would prefer namespaces, that way you can have private data in an anonymous namespace in the implementation file (so it doesn't have to show up in the header at all as opposed to private members). Another benefit is that by using your namespace the clients of the methods can opt out of specifying MyMath::
Why would I choose one over the other as a means of organizing my software?
If you use namespaces, you will frequently hit a language defect that functions which call each other must be listed in a specific order, because C++ can't see definitions further down in the file.
If you use classes, this defect does not occur.
It can be easier and cleaner to wrap implementation functions in a class than to maintain declarations for them all or put them in an unnatural order to make it compile.
One more reason to use class - Option to make use of access specifiers. You can then possibly break your public static method into smaller private methods. Public method can call multiple private methods.
Both namespace and class method have their uses. Namespace have the ability to be spread across files however that is a weakness if you need to enforce all related code to go in one file. As mentioned above class also allows you to create private static members in the class. You can have it in the anonymous namespace of the implementation file however it is still a bigger scope than having them inside the class.