Is it good or okay practice to use a namespace as a static class? For example:
namespace MyStaticFunctions {
void doSomething();
}
Versus:
class MyStaticFunctions {
static void doSomething();
}
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
There’s no such thing as a “static class” in C++, so from a C++ point of view you’re not using it “as a static class”, you’re using it “as a namespace”. It’s certainly accepted practice to use namespaces to group functions together.
It’s up to you, though, how big you want the groups to be. It’s not unusual for C++ libraries to use a single namespace for the whole public interface. That might come as a surprise to someone who is used to (say) Java, where classes are often used to group together smaller numbers of static methods. Since C++ was here first, you could say that Java is using classes as namespaces.
So, in C++ you don’t tend to see classes similar to
java.util.Collectionsorjava.lang.Math, full of static members. If you want groups of functions like that in C++, use namespaces.The exception (isn’t there always a special case in C++?) is traits types like
std::numeric_limits<T>, where the template parameter makes the class do something that a namespace can’t do. You could define a namespacenumeric_limitscontaining function templatesmax<T>(),min<T>()etc, but it’s not as good. Firstly, it groups things slightly differently, the typeTappears “lower down the hierarchy”. Secondly it doesn’t do everything that a traits type does, because there’s no such thing as an “object template” that would let you define a valuenumeric_limits::digits<T>.I don’t know C# well enough to comment on the practical uses of static classes there, but AFAIK it’s just a class restricted to having no non-static members, so it’s analogous to those Java classes.