Class VERSUS namespace, OR class AND namespace? [closed]
Asked Answered
L

3

13

Both Class and Namespace?

This question is about a pattern that I am seeing myself use more and more: Having both a class and a namespace for related concepts. I think this is motivated mainly by C++ language artifacts, but not totally.

I suppose the top level question is: Is this a good idea? Having both a class and a namespace for related concepts?

Lower level question:

What is the best way to do this?

Class nested within the namespace?:

namespace Foo_Namespace {
   class Foo_Class {
       ...
   };
}

Or separate, peer, class and namespace?:

class Foo_Class {
    ...
};
namespace Foo_Namespace {
   // non-class free functions, etc.
}

I must admit that I lean towards nesting the class within the namespace. Even though it leads to ugly names. But even if I do that, what naming conventions should I use:

The following is too long, leading to really ugly names Foo_Namespace::Foo_Class

namespace Foo_Namespace {
   class Foo_Class {
       ...
   };
}

It isn't necessary to use any suffixes or indicators in the name:

namespace Foo {
   class Foo {
       ...
   };
}

But then I find myself uncertain, when I look at Foo::bar(), if that is a free function bar in namespace ::Foo, i.e. ::Foo::bar(), or a member function in class Foo in namespace ::Foo::Foo::bar().

And names like ::Foo::Foo::bar are still not, umm, nice.

Currently I am doing

It isn't necessary to use any suffixes or indicators in the name:

namespace Foo_ns {
   class Foo {
       ...
   };
}

mainly because I usually create the class first, and then later realize that a namespace would be nice.

I wonder if I should revive a naming convention I haven't used in years: _c for class, _ns for namespaces:

namespace Foo_ns {
   class Foo_c {
       ...
   };
}

Details:

I won't repeat what I have said above, but I'll add a bit more.

The most practical reason I know of to use a namespace in addition to a class is that you are allowed to do forward declarations of free functions in a namespace, but you are not allowed to do forward declarations of some methods of a class. I.e. with a class you have to declare it all or nothing. Whereas with free functions in general, and free functions in namespaces in particular, you can declare it piecemeal. Parts can be declared in different header files. Rather than #including a massive header-only-library for a massive class, you can use forward declarations for just one or two functions. Etc.

(See, for example, http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Forward_Declarations, although Google netly comes down against forward declarations rather than including a header.)

Another reason is that a namespace allows the class itself to be kept small.

The biggest advantage for a class is that a class can be passed to a template, whereas a namespace cannot be.

I prefer to have the class nested within the namespace, Foo_ns/Foo_ns::Foo_c rather than to have them as peers Foo_ns/Foo_c, because often a class needs helper classes, e.g. Foo_ns/Foo_ns::Foo_c/Foo_ns::Foo_Helper_c. If the class and the namespace are peers, it seems strange to have Foo_ns/Foo_c but Foo_ns::Foo_Helper_c.

I like namespaces, because I agree with Andrei Alexandresciu: http://laser.inf.ethz.ch/2012/slides/Alexandrescu/1-C++%20course%20parts%201%20and%202.pdf

 Class methods vs. free functions

 • Conventional wisdom: methods are cool, free functions are so 1960s
 • Yet:
   ◦ Free functions improve encapsulation over methods
   ◦ Free functions may be more general
   ◦ Free functions decouple better
   ◦ Free functions support conversions on their left-hand argument

  Surprising fact #2

    Making a function a method should be
    your last, not first, choice

  (c) 2012– Andrei Alexandrescu. 32 / 59

It's better to create free functions than methods in classes.

But sometimes classes just have to be used - e.g. for templates.

Naming convention wise

I used Foo_ns / Foo_ns::Foo_c in the past

I'm using Foo_ns / Foo_ns::Foo now

(By the way, I tend to use Class_Names_With_Underscores_and_Initial_Caps, not CamelCase.)

If it makes sense, I might elide the _ns suffix on the namespace - e.g. where the namespace and the class(es) do not need to have the same name.

I dislike making them having the same name. Consider a constructor for a class Foo inside a namespace foo:

::Foo::Foo::Foo() vs ::Foo_ns::Foo::Foo()

The latter is not much better, but is a bit less confusing.

I think that I usually create the class on its own, without nesting it in a namespace. In fact, I probably add a few static methods, before I realize that a class nested within a namespace would be better. By that stage it may be a pain to refactor, and I sometimes end up creating forwarding functions, that forward from the class static method to the free function in the namespace, or vice versa. This causes me to regret bot to jump to class wthin namespace right from step 1.

Conclusion

My current BKM is Foo_ns / Foo_ns::Foo, i.e.

namespace Foo_ns {
   class Foo { 
   ...
   };
}

I'd appreciate any suggestions, any improvements.

Or am I just broken for doing this?

Lovellalovelock answered 19/1, 2013 at 21:15 Comment(4)
This is really much up to each own. I personally like to group related functions and classes inside a namespace. Lets say I'm making a networking program, then all functionality that has to do with the actual networking would end up in a net namespace, while configuration (like compile-time and run-time configuration and argument parsing) ends up in a config namespace. But that's just me.Syrup
About your confusion whether it is a member function or a freestanding function in a namespace: That's where naming guidelines come in handy. Never seen a naming guide that didn't make the distinction between the two handy for obvious reasons and I'd say any guide that does that should only be used for backcomp reasons only. Google uses CamelCase for classes and all lower case for namespaces.Tumefacient
@Voo: I consider a namespace to be an open class that doesn't have object instances.Lovellalovelock
@KrazyGlew Well since you yourself already admit the confusion of naming namespaces and classes identical, I'd think you should see the value of changing your naming guidelines in that regard ;) foo::bar() vs. Foo::bar() makes it very clear what's going on.Tumefacient
C
14

I recommend having your class in a namespace with related functions. A big reason for this is argument-dependent lookup (ADL). When you call a non-member function that has a class type argument, the function name is looked up in the enclosing namespace of that class. So if you have, say:

namespace foo {
  class bar { };
  void baz(bar);
}

If you ever want to call baz, you won't need to explicitly give the namespace it is contained in, you can simply do:

foo::bar x;
baz(x);

Without qualifying baz, the compiler still found the function because it is within a namespace that encloses the type of its argument. In this way, C++ considers the contents of the enclosing namespace of a class to be part of the interface of that class. Implementing functions that are part of the interface of a class as non-member non-friend functions in this way, allowing ADL to find the function, increases encapsulation. If a function doesn't need access to the internals of a class, don't make it a member of that class - instead, put it in the same namespace as that class.

It's suspicious that your namespace has the same name as your class, however. Usually there will be more than one class within a namespace, and even if there weren't, the names would be different. The name of the namespace should describe its contents, not just the single class inside it.

Conway answered 19/1, 2013 at 21:27 Comment(2)
+1 for C++ considers the contents of the enclosing namespace of a class to be part of the interface of that class.Inflow
ADL - good point. // As for more than one class within a namespace - I gues what I am saying is that is where I have normally switched over to namespaces, but I am now considering switching over even earlier, even if there is only one class within the namespace.Lovellalovelock
T
4

Separate Foo_Class and Foo_Namespace is definitely wrong, it will prevent you from using Argument Dependent Lookup to find functions in the namespace that are meant to be used with the class.

So the class should be nested within the namespace if there will be functions in the namespace taking arguments of the class type.

Using the same name for the class and namespace is a bit confusing, possibly leading to ambiguities in some cases.

It's also unusual to name a namespace with an initial uppercase letter. If your class names start with an uppercase letter you could go for namespace foo and a class Foo, giving foo::Foo.

Is the namespace not going to contain more than one class? That sounds unusual to me. I would name the namespace after all its contents, just not one type. If it's a socket class I'd put it in a networking namespace, for instance.

I think _c suffixes on classes is completely ridiculous. I don't like the _ns suffix on namespaces either, its only saving grace would be that Foo_ns::Foo is better than Foo::Foo but I'd still make it foo::Foo instead.

(The rest of your question just seems to be "why are namespaces good" which shouldn't really need explaining, they were added to the language for a reason, and the good advice to use non-members for parts of the interface which don't need to be members. Google are right, in general use headers not forward declarations, that doesn't change the fact that you can re-open namespaces in separate headers to add new names to the namespace, which is the advantage you're describing.)

Talca answered 19/1, 2013 at 21:25 Comment(0)
M
2

I dislike "fractal" names repeating things and try to avoid it. For your case, I'd try something like namespace "Foo" and nested class "Type". Maybe some other name would be more appropriate, but that depends on your actual use case. Here's a use case that I find myself repeating over and over:

namespace status {
    enum type {
        invalid,
        okay,
        on_fire
    };
    // debug output helper
    char const* to_string(type t);
}

The enumeration type is called status::type, which can take values like status::okay. Pretty readable IMHO.

Merrick answered 19/1, 2013 at 21:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.