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.
Related
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.
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.
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
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.
I occasionally have classes with private static data members. I'm currently debating if I should replace these with static variables in an unnamed namespace in the implementation file. Other that not being able to use these variables in inline methods, are there any other drawbacks? The advantage that I see is that is hides them completely from the users of the class.
I'm not convinced that the benefit is worth the readability impact. I generally consider something that's private to be "hidden enough."
1) There is a drawback in the form of an added restriction on binary organization. In a presentation at a C++ conference in the 1990s, Walter Bright reported achieving significant performance increases by organizing his code so that functions that called each other were in the same compilation unit. For example, if during execution Class1::method1 made far more calls to Class2 methods than to other Class1::methods, defining Class1::method1 in class2.cpp meant that Class1::method1 would be on the same code page as the methods it was calling, and thus less likely to be delayed by a page fault. This kind of refactoring is easier to undertake with class statics than with file statics.
2) One of the arguments against introducing the namespace keyword was "You can do the same thing with a class," and you will see class and struct being used as a poor-man's namespace in sources from the pre-namespace era. The convincing counter-argument was because namespaces are re-openable, and any function anywhere can make itself part of a namespace or access a foreign namespace, then there were things you could do with a namespace that you could not do with a class. This has bearing on your question because it suggests that the language committee was thinking of namespace scope as very much like class scope; this reduces the chance that there is some subtle linguistic trap in using an anonymous namespace instead of a class static.
I disagree with the other answers. Keep as much out of the class
definition as possible.
In Scott Meyers' Effective C++ 3rd edition he recommends preferring non-friend
functions to class methods. In this way the class definition is as
small as possible, the private data is accessed in as few places as
possible (encapsulated).
Following this principle further leads to the pimpl idiom. However,
balance is needed. Make sure your code is maintainable. Blindly,
following this rule would lead you to make all your private methods
file local and just pass in the needed members as parameters. This
would improve encapsulation, but destroy maintainability.
All that said, file local objects are very hard to unit test. With
some clever hacking you can access private members during unit tests.
Accessing file local objects is a bit more involved.
It not only hides them from users of the class, it hides them from you! If these variables are part of the class, they should be associated with the class in some way.
Depending on what you are going to do with them, you could consider making them static variables inside static member functions:
// header file
class A {
public:
static void func();
};
// cpp file
void A :: func() {
static int avar = 0;
// do something with avar
}
I guess it boils down to whether these variables have some actual meaning in the context of the class (e.g., pointer to some common memory used by all objects) or just some temporary data you need to pass around between methods and would rather not clutter the class with. In the latter case I would definitely go with the unnamed namespace. In the former, I'd say it's a matter of personal taste.
I agree partly with Greg, in that unnamed namespace members aren't any more encapsulated than private data. The point of encapsulation, after all, is to hide implementation details from other modules, not from other programmers. Nevertheless, I do think there are some cases where this is a useful technique.
Consider a class like the following:
class Foo {
public:
...
private:
static Bar helper;
};
In this case, any module that wants to use Foo must also know the definition of Bar even though that definition is of no relevance what-so-ever. These sort of header dependencies lead to more frequent and lengthier rebuilds. Moving the definition of helper to an unnamed namespace in Foo.cpp is a great way to break that dependency.
I also disagree strongly with the notion that unnamed namespaces are somehow less readable or less maintainable than static data members. Stripping irrelevant information from your header only makes it more concise.