Class VERSUS namespace, OR class AND namespace? [closed]

家住魔仙堡 提交于 2019-12-21 07:27:14

问题


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?


回答1:


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.




回答2:


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.)




回答3:


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.



来源:https://stackoverflow.com/questions/14418959/class-versus-namespace-or-class-and-namespace

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!