Use namespaces or prepend vendor's name when naming classes? - c++

Currently I'm working on the project that is just born. Previous developers used to name each class prepending a shorten vendor name i.e. CssMainWindow. (Css stands for Cool Software Solutions).
My question is: Shouldn't namespaces be used here? Then names of classes become much nicer.
That is:
namespace Css {
class MainWindow {
//...
};
}
What are the (ad|dis)vantages of both methods?

Appending a prefix makes the class name longer and it takes longer to type. That's the only disadvantage I can think of.
Using namespaces.... well you can just put
using namespace Css;
at the beginning of your files and file origin will be lost along with that.
I guess in the end it's up to the developer. There are 2 reasons I can think of why someone would want to identify classes:
1) For a sense of ownership. In that case, appending a prefix is, IMO, the way to go. People using your code will know it's YOUR code :).
2) For grouping classes together - in which case a namespace makes more sense.

It would depend. If your vendor-specific classes include some things like e.g.
tuple, make_tuple
string, vector
you may well wish to prefix, so as to prevent ugly ADL clashes1, and general inconvenience when people are expected to be using using namespace XXX. Popular libraries already have used that strategy (XString (Xalan), QString (Qt), CString (MFC) etc)
1 What are the pitfalls of ADL?

My suggestion: Always use namespace!
I will show several advantages of namespace:
// MainWindow.h
namespace Css {
class MainWindow {
// ...
};
};
// Other.cpp
namespace Css {
// An advantage is you don't always need to write the namespace explicitly.
MainWindow* window; // Not Css::MainWindow or CssMainWindow.
}
// In some cpp files
using namespace Css; // Never do this in header file or it will cause name pollution.
MainWindow* window; // You don't need to write Css:: in the whole file.
I can't recall any disadvantage of using namespace.

First things first.
Whatever the final choice, you should avoid as much as possible writing anything in the global namespace. You risk to face name clashes there. Therefore, your software should always be in a namespace of its own, and it's better if the name differs from those used in the libraries you depend of (reminder std is reserved already).
Once you have this namespace, then you normally don't need prefixing any longer. At least, not with the project name.
However it is mostly a matter of taste, and I have seen argued in the past that it made it easier to immediately identify where the class came from in the absence of IDE... I personally consider it and outdated habit inherited from C.

Related

C++ Namespace versioning

In C++ its possible to do the following for namespace versioning
First version:
namespace A__v1 {
class X ...
class Y ...
class Z ...
}
namespace A = A__v1
Second version (where the X class is changed):
namespace A__v1 {
class X ...
class Y ...
class Z ...
}
namespace A__v2 {
class X ...
using A__v1::Y;
using A__v1::Z;
}
namespace A = A__v2
What i would like to know is, is it worth the effort? Does this really add any advantage to your application/library when changing the internals of a namespace?
I actually like the non-macro way of handling this, it allows one build of the library to serve many versions. This will inevitably increase library size (due to more versions of some classes all being present) but there is one caveat though: the compiler will most likely report the full namespace qualification of the classes, making the user of your library, who doesn't know about your non-standard versioning scheme very confused.
On second thought, I also don't see the use of supplying two versions of the same thing in one library build, except if there are different CPUs/architectures involved, but I don't think that's what you're getting at. Keeping old versions of classes around is not smart, people will never switch to the newer ones if they don't need to, and if something (half-internal) gets deprecated, you'll have removed something that was "part of the library" so to speak.
It's a nice trick and quite useful but there are some problems to be aware of. Mostly, you can't specialize a template using the name A for the namespace.
C++0X have inline namespaces which was designed to handle this better.
the library can be tricky for the programers who will use that namespace, maybe it's better to use separate namespaces independently to make the difference.

Avoiding Over-Use of Namespaces

My library uses several nested namespaces, laid out like the following:
Library name
Class name 1
Class name 2
Class name 3
[...]
Utilities
Class name 1
[...]
Class name 2
[...]
Class name 3
[...]
[...]
The "Utilities" namespace contains useful extensions to each of the classes that don't warrant being included in the actual class itself.
The "Library name" namespace is necessary because it avoids broad conflicts with other libraries, the "Utilities" namespace is necessary to avoid the type of ambiguity that arises from things like this, and the "Class name" namespaces inside it avoid name clashes between utilities written for similar classes.
Despite this, it's still an enormous hassle in practice. Take the following, for example:
MyLibrary::MyContainer<int> Numbers = MyLibrary::Utilities::MyContainer::Insert(OtherContainer, 123, 456);
// Oh God, my eyes...
This makes me think I'm doing something seriously wrong. Is there an easier way to keep things organized, intuitive and unambiguous?
Look at how the standard library (or boost) is organized. Nearly all of it is inside the single std namespace. There's just little to be gained by putting everything inside its own namespace.
Boost puts most things inside boost, while major libraries get a single subnamespace (boost::mpl, or boost::filesystem, for example). And libraries commonly define a single aux subnamespace for internal implementation details.
But you don't typically see deep or fine-grained namespace hierarchies, because they're just painful to work with, and there's little to no benefit from them.
Here are some good rules of thumb:
Helper functions related to a specific class should be in the same namespace as the class, to enable ADL to work. Then you don't need to qualify the name of the helper function at all when calling it. (Like how you can call sort instead of std::sort on iterators defined in std).
For everything else, remember that the purpose of namespaces is to avoid name clashes and not much else. So all your library should be in a namespace, to avoid clashes with user code, but within that namespace, there's no technical need for further subnamespaces unless you plan to introduce clashing names.
You may want to separate internals of your library into a sub-namespace, so users don't accidentally pick them up from the main namespace, similar to Boost's aux.
But generally, I'd suggest as few nested namespaces as possible.
And finally, I tend to make a point of using short, easy-to-type and easy-to-read names for my namespaces (again, std is a good example to follow. Short and to the point, and nearly always without further nested namespaces, so you don't get a cramp from having to write it often, and so it doesn't clutter your source code too much.)
Just the first rule about helper functions and ADL would allow your example to be rewritten like this instead:
MyLibrary::MyContainer<int> Numbers = Insert(OtherContainer, 123, 456);
Then we could rename MyLibrary to, say, Lib:
Lib::MyContainer<int> Numbers = Insert(OtherContainer, 123, 456);
and you're down to something pretty manageable.
There shouldn't be any clashes between similar utility functions for different classes. C++ allows you to overload functions, and specialize templates, so that you can have both an Insert(ContainerA) and Insert(ContainerB) in the same namespace.
And of course, clashes between namespaces and classes are only possible if you actually have additional nested namespaces.
Remember that within your Library namespace, you alone dictate which names are introduced. And so you can avoid name clashes just by, well, not creating any clashing names. A namespace to separate user code from library code is important because the two may not know about each others, and so clashes can occur unintentionally.
But within your library, you can just give everything non-clashing names.
If something hurts, stop doing it. There is absolutely no need to use deeply nested namespaces in C++ - they are not intended to be architectural devices. My own code always uses a single level of namespaces.
If you insist on using nested namespaces, you can always create short aliases for them:
namespace Util = Library::Utility;
then:
int x = Util::somefunc(); // calls Library::Utility::somefunc()
A declaration in a header file necessitates the namespacing to not pollute the global namespace:
MyLibrary::Utilities::MyContainer<int> Numbers;
But in the source file you can use usings:
using namespace MyLibrary::Utilities;
...
MyContainer<int> Numbers;
Numbers.Insert(OtherContainer, 123, 456);
The fully qualified name doesn't actually look that bad to me, but I like being explicit in method and class names. But using can help things out:
You could probably get away with a using namespace MyLibrary at global scope in your source files, making it:
MyContainer<int> Numbers = Utilities::MyContainer::Insert(OtherContainer, 123, 456);
And then you can import the specific functions you need:
using MyLibrary::Utilities::MyContainer::Insert
and then
MyContainer<int> Numbers = Insert(OtherContainer, 123, 456);

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.

c++ Namespace headaches

Okay, this question has evolved a bit, and I want to try to start (over) with the basic goals I'm shooting for:
Create library code that wrappers legacy C-language entities in C++ resource acquisition is initialization and also provides basic or better exception guarantee.
Enable clients of this code to use it in a very natural C++ fashion w/o creating a lot of overhead to existing code to convert it to use the C++ wrapper objects (i.e. automatic conversion to appropriate legacy types, constructors that take legacy types, etc.)
Limit the namespace impact of the library code. Ideally, The library would have several sub-namespaces that provide related functionality that limit the volume and impact of using namespace X type declarations - much as the boost libraries do (i.e. use of details namespaces to only inject those symbols that the user would reasonably want to use, and hide those that are implementation details; also limit the extent of possible new meanings to existing symbols, to avoid surprising implicit conversions within user-code)
Require that clients explicitly ask for those parts of the library that they actually want to inject into their code base. This goes hand in hand with limiting the impact of inclusion of the the library's headers. The client code should have a reasonable level of control over which parts of the library are going to be automatically used for name-resolution when they compile their code.
My own library code should not have to be riddled with refactor-brittle code constructs. It would be ideal if the library's headers didn't have to constantly declare private typedefs in order to have access to the rest of that section of the library. Or in other words: I want my library to be able to be written as intuitively as my clients get to when making use of said library. Name resolution should include the namespace that the library is defined within in addition to any others that have been explicitly "using'd".
I come across this scenario often, and am looking for a better way...
I have a class, C in namespace N. C has a member, Free. It free's something that C manages, and allows C to manage a new thing.
There are several global Free functions. There are also a few helper functions in the same namespace N as C, one of which is a helper that free's the thing managed by C, named free.
So we have something like:
namespace N {
void free(THING * thing);
class C
{
public:
... details omitted...
free()
{
free(m_thing); // <- how best to refer to N::free(THING&)
}
}
} // namespace N
I could use N::free(m_thing). But that seems unfortunate to me. Is there no way to refer to that which is outside the class scope but without resolving absolute namespace (a relative one step out scope-wise)?
It seems to me that having to name N::free is obnoxious, since you wouldn't have to if this were a free-standing function. Nor would you need to if the class's method name happened to be different (e.g. dispose). But because I've used the same name, I cannot access it without having to specify what amounts to an absolute path - rather than a relative path - if you'll indulge me the analogy.
I hate absolute paths. They make moving things around in namespaces very brittle, so code-refactoring becomes much uglier. Plus, the rules of how to name things in function bodies becomes more complex with the current set of rules (as I understand them) - less regular - inducing a schism between what one expects and what one gets as a programmer.
Is there a better way to access free-standing functions in the same namespace as a class without having to absolutely name the free-function absolutely?
EDIT:
Perhaps I should have gone with a less abstract example:
namespace Toolbox {
namespace Windows {
// deallocates the given PIDL
void Free(ITEMIDLIST ** ppidl);
class Pidl
{
public:
// create empty
Pidl() : m_pidl(NULL) { }
// create a copy of a given PIDL
explicit Pidl(const ITEMIDLIST * pidl);
// create a PIDL from an IShellFolder
explicit Pidl(IShellFolder * folder);
...
// dispose of the underlying ITEMIDLIST* so we can be free to manage another...
void Free();
};
So ITEMIDLIST* come from a variety of places, and are destroyed with CoTaskMemFree(). I could introduce Pidl as a global name - as well as all of the helper functions in the "Windows Shell.h" header that is part of my toolbox library.
Ideally, I would segment some of the tools in my library by what they relate to - in this case the above all relates to COM programming in Windows. I have chose Toolbox as the base namespace for my libraries stuff, and was currently thinking I'd use Toolbox::Windows for very windows-y functions, classes, etc.
But the C++ namespace and name-resolution rules seem to make this very difficult (hence this question). It makes it very unnatural to create such segmentation of my code - since koenig lookup fails (since ITEMIDLIST is not in my Toolbox::Windows namespace), and I don't have the ability to move it there! Nor should I. The language should be flexible enough, IMO, to both allow for extension libraries such as my Toolbox library to extend other folks code without having to inject my extensions into their namespace (which, in the case of Win32 and the general vast majority of code that exists today, is the GLOBAL NS - which is the whole point of making namespaces in the first place: to avoid global NS crowding / pollution / ambiguity / programming surprises).
So, I come back around to, Is there a better way to do this: Extend existing libraries of code while not polluting their NS with my extensions but still allow for intuitive and useful name resolution as one would expect if my code were in their NS but explicitly introduced by the client of my code (i.e. I don't want to inject my code willy-nilly, but only upon explicit request)?
Another Thought: Perhaps what would satisfy my above criterea would be if I had the following:
using namespace X {
code here...
}
Where I could place such a construct anywhere, including in a header, and I would not have to be concerned about dragging X into my client's code, but I would have the same freedom to write my source code as I would if I were in the root namespace.
I don't see to avoid having to qualify namespace-scope free() here, but it should be noted that this is not the same as an "absolute path". For one thing, if you have nested namespaces, you only have to refer to the innermost one:
namespace N1 {
namespace N2 {
namespace N3 {
void free(THING * thing);
class C {
public:
free() {
N3::free(m_Thing); // no need to do N1::N2::
}
};
}
}
}
[EDIT] in response to edited question. Again, I do not see any way to do this in the exact scenario that you describe. However, it doesn't seem to be idiomatic C++ approach - the more common way to do the same is to provide your own wrapper class for ITEMIDLIST that manages all allocations, RAII-style, and exposes the original handle (e.g. via conversion operators a la ATL, or an explicit member function like c_str() if you want extra safety). That would remove the need for your free altogether, and for any other free function that you might want there, since you control the wrapper type and the namespace it's in, you can use ADL as usual.
[EDIT #2]. This part of the question:
allow for intuitive and useful name resolution as one would expect if my code were in their NS but explicitly introduced by the client of my code (i.e. I don't want to inject my code willy-nilly, but only upon explicit request)?
Isn't this precisely what you putting it in a namespace, and your client writing using namespace ..., will achieve?
You have two options:
Fully qualify function name.
Let Koenig lookup do the job (if THING belongs to namespace N).
I'd choose the first one with such popular function name as free.
Alternate option is to use m_thing->Release() or something like that.
Yuu could write ::free(m_thing);. This will call the global free() function. However, if you have another free() function outside the N namespace, you've got yourself into trouble. Either change names of some of your functions or use the function name with explicit namespace.
It seems to me that there is a problem of design here.
I find strange to have the same identifier used both as a free-function and a class method, it really is confusing. I try to minimize the occurence as much as possible, although I admit that it happens for swap...
I try not to qualify the names within the method, but here of course you run the risk of hiding, where MyClass::free hides the N::free method, which never participates in the lookup... tried to find about the scope resolution here but could not find the exact passage.
For swap I simply use:
class MyClass
{
void swap(MyClass& rhs)
{
using std::swap; // Because int, etc... are not in std
swap(m_foo, rhs.m_foo);
swap(m_bar, rhs.m_bar);
}
};
inline void swap(MyClass& lhs, MyClass& rhs) { lhs.swap(rhs); }
Therefore I make sure that the right method will be included in the lookup, and avoid falling back on a 'global' method if any.
I prefer this approach to explicit naming and usually bolts using and typedef declaration at the top of the method so that the actual code is not bloated.
I would use a completely different approach to what you are trying to accomplish. I think you need a bit of redesigning. Remove the globals and make a factory/abstract factory that will fabricate (create an instance of your class) and destroy it with the destructor. In fact, that would be the RAII idiom.