C++: Refactoring managing namespaces - c++

I am refactoring a widely used class. Given how widely it is used, my intend is to create a version 2 of the class. I will keeping the interfaces same/similar [I am forced to make some changes, otherwise it will become ugly with new changes] so that switching from old class to new class becomes easy. And we can switch applications using the old class to new class one by one.
Now I am not sure how to manage name / namespace in this case.
Eg:
Currently, lets say, the class is under a namespace 'app'
namespace app {
class Important {
...
};
}
I would like to keep the class name same or very similar so that the meaning is clear.
namespace app {
// This looks okay (conveys the meaning), but is ugly.
class Important2 {
...
};
}
namespace app {
namespace v2 {
// I think this will be confusing. It will given a feeling that the v2
// applies to app namespace. There are lot of classes under 'app'
// namespace which are not changed.
class Important {
};
}
};
Is there a better approach?
Thanks!

I think the best solution to your problem is to used the gof factory design pattern, where you have an interface and a number of implementations for example Important, Important2 etc.
You could then tell your consumer that you will be deprecating Important soon but a compiler warning

You could resolve via simple namespace alias.
A sample could be in this answer https://stackoverflow.com/a/41420638/781933, for a switch on/off approach (driving migrations on a per-project base).
If instead you have to go through intermediate compositions rather than a complete replacement you could adopt intermediate solutions with compositions and inline namespaces.
You can find a specific example of version management via namespacing in the Stroustrup's The C++ Programming Language.

Related

Why is Microsoft using struct rather than class in new code?

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.

How should we implement utility/helper modules in C++?

1) utility class, use only static methods, block copying and creation
class myUtils
{
public:
static void utilFunc();
static void utilGreatFunc();
private:
utils() { } // block creation
utils(const utils &) { }
~utils() { }
}
2) use namespace
namespace myUtils
{
void utilFunc();
void utilGreatFunc();
}
what is the best way of doing this? I suppose the namespace way, it is much clearer to me and simpler to write. Or maybe there is some other and better design?
You never use a "utility class with static methods" in C++. That's a Java-ism. Instead, use your second solution and put the functions in a namespace.
Several years ago there were lots of discussions about helper classes that you can still search and read. My opinion about this is helper classes are a bad smell almost always (an strong one). They let us see the programmer didnĀ“t know where to put his code and then he created a MyBagOfThingsHelper class which breaks the most basics principles of OOP.
Probably, the most important is the SRP. Ask yourself: which is the responsibility of that MyBagOfThingsHelper class?
What about the strong coupling it creates?
I know this is neither what you asked for nor what you want to read but the best is neither namespaces nor classes but avoid them, avoid them.

C++: Is there a way to create a templated namespace?

I was wondering if it would be possible to do the following:
template <typename T>
namespace basic_foo {
struct str {
T value;
};
}
basic_foo<char>::str s1;
namespace foo = basic_foo<char>;
foo::str s2;
Is it possible to do this in any c++ compiler?
Is there work being done to implement this?
I think that it would be a great addition to the language.
Thanks in advance.
No, you cannot define a namespace template. You can, however, achieve almost exactly what you want (with only slightly different syntax), by making basic_foo a class template:
template <typename T>
struct basic_foo {
struct str {
T value;
};
};
basic_foo<char>::str s1;
typedef basic_foo<char> foo;
foo::str s2;
No, but you can use templated struct:
template<typename T>
struct basic_foo
{
struct str
{
T value;
};
};
typedef basic_foo<char> foo;
foo::str s1;
You could also use class instead of struct, but you would have to remember about public: in such case.
No. It`s impossible, namespace template is unreal, but you can make class template.
The other answers explain how to do what it looks like you might want. But it sounds like you have a different idea of what a namespace is for than what it really is designed for.
namespace solves the problem of two unrelated C++ code bases being able to communicate with each other. C doesn't have namespaces and is much more verbose as a result. Try using a 3rd party library such as openssl or oauth in C. You'll find a lot of function calls like this:
openssl_create
openssl_connect
and so on. And this is really, really important. Because chances are I want to write a function called connect. And so does the author of the ZMQ library I used. And so forth. And it's a major, major pain to have two functions with the same name trying to be called in the same place...
namespace is purely a software engineering construct, not a programming one. It lets the prefix openssl_ simply become the namespace so code like the above can intermingle more freely. Why don't namespaces conflict? This is where software engineering becomes even more human and social, as essentially the global programming community must make sure this doesn't happen. Generally outer namespaces are usually companies; I would guess all Google internal code is in namespace Google. Java solves this by promoting the convention of naming package (like namespace) by the internet domain name, which is presumably a real-world entity that can't conflict, e.g. Google code should live in package com.google...
I should also note that within an organization namespaces are used at the application, or product, or team level - e.g. Google Drive probably has a function "upload" somewhere as does Google Mail, and those teams might generally not talk to each other... but still need to write intermingling code.
That's what namespaces do. Nothing more, nothing less.

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

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.

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.