My project is divided into modules and they all share a similar structure, instead of writing classes like EntityHandler and InputHandler, I'd like to use namespaces and do Input::Handler and Entity::Handler. Now this all seems good to me, but those namespaces are also nested inside one more namespace which also have a Handler class!
Some people said that this is bad practice and could be confusing, but as part of my style I never use the using <namespace>; keyword so it will always look explicit. Do you think this would be good practice, and if not can you tell me where this could come back to bite me down the line?
I'm sorry if this has been asked before, the places I looked didn't give good explanations as to why or why not to do this!
I think it is better to fully qualify namespace without using because it allow to get rid of some mistakes when reading and/or compiling code. In many tutorials it is recommended to use fully qualify namespace i.e. void doSome (std::vector& data) in function declaration instead of placing using namespace std + doSome (vector& data) . It is good practice to fully qualify namespace because it allow to reduce type resolve ambiguity errors on a compilation stage. Consider following example:
class A {
private:
Super::Handler* _handlerOne;
Super::Entity::Handler* _handlerTwo;
};
It would be hard to do the same when you will be use using:
using namespace Super;
using namespace Super::Handler;
class A {
private:
Handler* _handlerOne; // What type compiler place here ??? , we don't know ...
Handler* _handlerTwo; // What type compiler place here ??? , we don't know ...
};
Less ambiguities - better code.
Related
So normally I wouldn't ask a question like this because it seems like it could be opinion based or start some sort of verbal war on coding practices, but I think there might be a technical reason here that I don't understand.
I was looking over the code in the header files for vcpkg (a library packing manager that Microsoft is creating and is "new" code) because reading code generally is a good way to learn things you didn't know.
The first thing I noticed was the use of using rather than typedef.
Snippet from 'https://github.com/microsoft/vcpkg/blob/master/toolsrc/include/vcpkg/parse.h'
template<class P>
using ParseExpected = ExpectedT<std::unique_ptr<P>, std::unique_ptr<ParseControlErrorInfo>>;
I haven't personally used using this way before and an answer from: What is the difference between 'typedef' and 'using' in C++11?. Essentially, using is the new way to do it, and the benefit is that it can use templates. So Microsoft had a good reason to use using instead of typedef.
Looking at 'https://github.com/microsoft/vcpkg/blob/master/toolsrc/include/vcpkg/commands.h' I noticed that they did not use any classes. Instead it was only namespaces with a function or so in them. ie:
namespace vcpkg::Commands
{
namespace BuildExternal
{
void perform_and_exit(const VcpkgCmdArguments& args, const VcpkgPaths& paths, const Triplet& default_triplet);
}
}
I'm guessing that part of this is that the calling syntax looks essentially just like a static member function in a class, so the code performs the same but maybe saves some overhead by being a namespace instead of a class. (If anyone has any ideas on this too that would be great.)
Now the main point of all this. Why is Microsoft using structs instead of classes in their namespaces?
Snippet from 'https://github.com/microsoft/vcpkg/blob/master/toolsrc/include/vcpkg/parse.h':
namespace vcpkg::Parse
{
/* ... Code I'm excluding for brevity ... */
struct ParagraphParser
{
ParagraphParser(RawParagraph&& fields) : fields(std::move(fields)) {}
void required_field(const std::string& fieldname, std::string& out);
std::string optional_field(const std::string& fieldname) const;
std::unique_ptr<ParseControlErrorInfo> error_info(const std::string& name) const;
private:
RawParagraph&& fields;
std::vector<std::string> missing_fields;
};
}
Searching stackoverflow, I found an old question: Why Microsoft uses a struct for directX library instead of a class?
Which the answers were essentially, you don't have to declare things as public as default and a comment way at the bottom saying that it was old code.
If vcpkg was old code I would be completely satisfied, however, this is new code. Is it just some style they have that is a carry over (but using vs typedef isn't)? Or is it to save a line of code (public:)? Or is there some sort of overhead benefit? Or some other thing I haven't considered at all?
The only differences between struct and class are:
the default member access (public vs private) and
the default inheritance if you inherit from the type (public inheritance vs private inheritance).
The end result of 1 will be the same once the author has finished adding public:/private: to the type. 2 you can easily control yourself by being explicit when you inherit, rather than rely on the default. It's hardly a big deal and doesn't really matter.
As to why Microsoft uses struct rather than class in their code, you will have to ask some Microsoft people.
Regarding the free functions vs static functions, I don't think there is any overhead in this with classes (I haven't measured this at all, I would just think that most compiler would recognize that the class is basically just a namespace for the function). The thing is just: You don't need a class.
Using a class with only static functions is basically abusing the class as a namespace. So if you are only doing that, then be explicit about it and just use a namespace. Having a class there would only be confusing since you would think that maybe there could be some state here and just see that there is non when you see that the function in the class is static.
This is especially relevant if this is used a bit wrongly. Imagine someone instantiates a class A a with static member function f to call a.f(). It is no problem regarding performance, since the construction is a no-op and it will pretty much be equivalent to A::f(). But for the reader it seems like there is some kind of state involved and that is just confusing.
Regarding the other two: using is just superior to typedef throught being able to use templates and is (IMO) better readable. The struct vs class issue is just something over what has the better defaults, its not a big difference, but most often, what you want is what a struct does, so there is no reason to use a class.
To be (more) compatible with C
To avoid making everything public by using the public: keyword, since that all COM objects for example have only public member functions.
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.
If I have a class :
class Foo{
public:
void someFunc():
}
Then in the implementation I need to do:
void Foo::someFunc(){
//My implementation.
}
Is there some way I can avoid having to prefix each function with Foo::, by using namespaces or something ? (just to save on typing.. no other reason).
EDIT: I don't see why this is down voted. If there was a C++ feature to structure code so we don't have to type as much, its actually worth knowing - similar to using the "Using" keyword so we don't have to prefix the namespace repeatedly...
EDIT: #PeteBecker Typing less is normally more maintainable (there is less code to maintain) - which is why we organise code into into constructs that allow us to share and reuse code. Correctness is not necessarily related to typing - but the less time you spend typing, the more time you have to spend on focusing on the idea or product, and whether your code is "correct". Prefixing a namespace or classname each time you refer to an object, does not make your code any more or less correct, but simply just takes time, and there is no reason to waste time doing things that are unnecessary. Which is why we have the "using" keyword for namespaces, so we won't have to type namespaces each time (I mentioned this earlier). So just like we have a "using" keyword for namespaces, I was asking if there was a way to do this for classes.
Only if you put the implementation directly in the header file.
Probably not what something that should be used but still a solution:
#define a Foo::
void a someFunc() ...
Sadly you can't with classes, but with namespaces you can:
test.h:
namespace Test {
void someFunc();
};
test.cpp:
namespace Test {
void someFunc() {
std::cout << "someFunc called" << std::endl;
}
};
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.
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.