How should we implement utility/helper modules in C++? - 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.

Related

Should I totally hide the internal class in my C++ header file when designing my SDK?

I am designing a SDK written in C++.
I have a question: could or should I totally hide the internal class in my public C++ header file?
The code snippets are like the following (in the header file MyPublicClass.h):
namespace PublicNamespace
{
namespace InternalNamespace
{
class MyInternalClass;
}
class MyPublicClass
{
public:
void SomeMemberFunc();
...
private:
std::shared_ptr<InternalNamespace::MyInternalClass> mImpl;
}
}
Per the C++ PImpl design pattern (and also many other materials from Google), it is OK to put the InternalNamespace::MyInternalClass into the public header.
My thought is: it looks unnecessary to let the external users know the internal namespace InternalNamespace, and also the class MyInternalClass. So I want to use void to replace the type InternalNamespace::MyInternalClass.
That's to say, for my case, I use std::shared_ptr<void> as the type of the data member mImpl, and in the .cpp file, use std::static_pointer_cast<InternalNamespace::MyInternalClass>(mImpl) to convert it to the actual class.
(Yeah, I know there is a little cost with this conversion but please ignore it).
Is this design correct or proper? Thanks all.
Don't use void or void * unless there is absolutely no alternative -- using void-pointers prevents the compiler from catching mistakes at compile-time, and leads to pain and suffering.
Using a clearly-labelled InternalNamespace should be good enough (assuming the programmers using your API aren't deliberately looking for trouble -- and if they are, there are plenty of other ways for them to find it anyway), although if you wanted to hide MyInternalClass entirely from calling code, you could instead make it an inner-class of MyPublicClass, i.e. something like this:
namespace PublicNamespace
{
class MyPublicClass
{
public:
void SomeMemberFunc();
...
private:
class MyInternalClass
{
[...]
};
std::shared_ptr<MyInternalClass> mImpl;
}
}
Since it's declared in the private section of MyPublicClass, no calling code outside of MyPublicClass would be able to access it at all.

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.

Singleton implementation: Is a namespace approach often preferable over a singleton class?

(This questions assumes that a global + unique object is the goal. I would like to clarify that this does not mean it is asking about or advocating the if/why/when of using/not-using singletons or globals.)
I am wondering if there's a technicality about C++ that I'm missing, so my question is:
Is a namespace implementation of the singleton pattern in C++ valid? And if so, is there a reason why it is not often suggested as the better approach?
From Google's style guidelines, we see namespace non-member functions recommended over static member function, but only when not sharing static data:
"Rather than creating classes only to group static member functions
which do not share static data, use namespaces instead."
Why shy away from letting non-member functions share static data, declared in an unnamed namespace? Is there something wrong about this that explains why namespaces aren't generally suggested as a better alternative to writing a singleton class in C++?
Because I can't find recommendations of the namespace approach, but it is very easy to find the class approach despite C++ not enforcing the use of classes:
C++ Singleton design pattern
Can any one provide me a sample of Singleton in c++?
Singleton instance declared as static variable of GetInstance method
http://www.aristeia.com/Papers/DDJ_Jul_Aug_2004_revised.pdf
Singleton: How should it be used
Using a named namespace with an unnamed namespace in its source file:
You can have 'state' via static data
You can gain the extra privacy of putting things in an unnamed namespace
You can still control the construction order of its static objects by using static pointers, and constructing from function calls.
You don't need to implement a singleton class
Edit - Example of namespace approach I was thinking:
SingleThing.h:
namespace single_thing // The singleton (if this is actually valid)
{
void GrowSomeCats(int amount); // Typical setter
int GetNumCats(); // Typical getter
}
SingleThing.cpp:
#include "Balloon.h"
namespace // Acting like private members and functions
{
int numCats = 4; // POD
Balloon* wilson = NULL; // Not POD (and not a singleton)
// Contrived 'private' function
bool CanGrowCats()
{ return wilson && wilson->LikesCats(); }
// Contrived excuse to instantiate non-POD 'members'
void RandomlyCreateOtherObjects()
{
if (!wilson /* && someRandomiserImTooLazyToType()*/ )
wilson = new Balloon();
}
}
namespace single_thing // 'Public' functions
{
void GrowSomeCats(int amount)
{
RandomlyCreateOtherObjects();
if (CanGrowCats())
numCats += amount;
}
GetNumCats()
{ return numCats; }
}
(I assume we can agree that global state is a dangerous thing that has to be used with special care.)
Technically your singleton namespace is equivalent to a singleton class. However it has one major drawback that makes it a no-go in my opinion: It hides the fact that it is stateful. Ever used std::strtok()? Remember what an atrocious mess it is? That’s because it hides its statefulness, too.
Because global state is inherently dangerous, any piece of functionality that uses it should make that fact abundantly clear at the call site, preferrably by using language constructs – because nobody reads comments or documentation. A Foo::instance()->do_work(); is a known pattern that makes it quite clear that something special is going on; a foo::do_work(); does not.
Singleton design pattern is about creation the only instance of a useful class (there is no need in creation of useless objects). In C++ classes are defined with class and struct keywords. To be useful a singleton class, beside creation and destruction, should also implement some methods that operate with the instance. To ensure singularity, a singleton class should hide its constructors and expose a static method for accessing the instance.
Using only namespaces one would not be able to define useful methods of the singleton. Implementing the instance access method as a function in a namespace instead of the class itself is possible, but would require 'friending' that function, and does not make sense because the class is already defined.
Implementing a non-object singleton (e.g. of a plain data type) would assume that the instance does not require construction and thus there is no need for singleton.

c++ when to put method out side the class

i saw that some times in c++ applications using only namespace declarations with header and source file like this :
#ifndef _UT_
#define _UT_
#include <string>
#include <windows.h>
namespace UT
{
void setRootPath(char* program_path, char* file_path);
char * ConvertStringToCharP(std::string str);
};
#endif
//and then in UT.cpp
#include "UT.h"
namespace UT
{
char * ConvertStringToCharP(std::string str)
{
char * writable = new char[str.size() + 1];
std::copy(str.begin(), str.end(), writable);
writable[str.size()] = '\0';
return writable;
}
void setRootPath(char* program_path, char* file_path)
{
//...
}
}
is it better then defining classic class with static methods?
or just simple class ?
dose this method has something better for the compiler linker ?
the methods in this namespace are called allot of times .
By shear coincidence I happen to read this answer for a slightly different question in Stack Overflow. In that the user rhalbersma had given a nice link to a Dr Dobb's article where the author Scott Meyers explains how methods implemented outside the class (non-friend methods), but inside the same namespace actually improve encapsulation. For me it was a good learning for today. Hope this helps you as well.
Performance-wise, there's no difference between having static class members and free functions in a namespace. It's a matter of logic though. Are your functions related to the class or not?
A good question to ask yourself - are you creating the static member functions inside the class just for better organization (or just so you can group them together)? If the answer is yes, you should probably use a namespace.
You put a method outside all classes when the method's meaning is independent of a class. Static classes in other languages (Java, C#) are a way to compensate for inability to put methods outside classes. Since C++ provides this ability out of the box through namespaces, the use of an additional "static class" would be counterintuitive to the readers of your code.
The primary reasons for using a static class member function is a logical and conceptual relation to the class and its members.
Another reason may be to enable template partial specialisation, which is not allowed for function templates, but for classes.
Otherwise, use a standalone function (defined in an appropriate namespace).
There's no absolute rule, but in general, unless the functions show a
very large degree of coherence, and you want to close the "namespace"
for some reason, so clients can't add functions to it, using namespace
is generally preferable to using class. Unless, of course, the intent
is to make them available to templates: you can instantiate a template
on a class, but not on a namespace. (This technique is often called
"traits"; a class with no non-static members is called a traits class.)
Even if you do use namespaces, you should define the functions:
void UT::setRootPath( char const* programPath, char const* filePath)
{
// ...
}
char* UT::convertStringToCharP( std::string const& str )
{
// ...
}
This way, any typos in the signature of the function will be detected by
the compiler.
By default you should always try to minimise the methods on a class. If you can implement functionality in terms of the class rather than within a class you should. In other words if you can achieve the desired functionality through using the already published public interface then you should. This vastly reduces the dependency of your code on implementation details.
So if you can then implement it outside of the class in an appropriate namespace that naturally seems related to the class.
EDIT: It appears that the OP is really asking about whether to implement a namespace or a static class as a holder object for utility/related functions. In my opinion namespaces are the correct way to do this, because that is what they are there for. A class is not necessary.

Static members class vs. normal c-like interface

Hey there.
After reading here about the Service Locator pattern, it got me thinking wether a class with only static members really is the way to go, or if a normal c-like interace wouldn't be more appropriate. I see people throwing around the class keyword all the time when they don't even need it.
Example with static members class taken from the linked page:
class Locator
{
public:
static IAudio* GetAudio() { return service_; }
static void Register(IAudio* service)
{
service_ = service;
}
private:
static IAudio* service_;
};
Here's a way one could do it too:
// in .h
namespace Locator{
IAudio* GetAudio();
void Register(IAudio* service);
}
// in .cpp
namespace Locator{
namespace {
IAudio* service_;
}
IAudio* GetAudio() {
return service_;
}
void Register(IAudio* service) {
service_ = service;
}
}
Both examples can be called exactly the same way with Locator::GetAudio() and Locator::Register(...).
Is one of the above superior to the other? Are they the same? Are there maybe better ways to accomplish this? Or is it just about personal preferences? Thanks for any help. :)
Your proposal with namespaces has a slight weakness in maintainability - if you need to change the interface for some reason, you have to remember to change both the interface (.h) and implementation (.cpp), or a mismatch may not be detected until link time. If you use a class, then the compiler can detect an error such as a number of parameters mismatch.
On the other hand, since the implementation (service_) in your case only appears in the .cpp file, you may be able to change the private implementation of the locator without forcing a recompile of code that depends on the locator. (Common class-based patterns can provide this same encapsulation.)
These are fairly minor differences. A public namespace containing functions is almost exactly the same as a class with only static member functions.
one good reason for using class interfaces is consistency.
often, there will be supporting implementation or subclass use of the shared data in the Locator class. therefore, it is preferable (to many people) to use one approach across their codebase, rather than combining namespaces and classes for their static data (since some implementations may extend or specialize the service).
many people don't like dealing with static data. some issues from the above examples are: thread safety, ownership, and the lifetime of the data. the data and the implementations can be easier to maintain if these are restricted to a class scope (rather than a file scope). these issues grow as the program's complexity grows -- the example you have posted is very simple.
namespace labels/aliases are more difficult to pass around (compared to types/typedefs/template parameters). this is useful if your interfaces are similar and you are using a good amount of generic programming, or if you simply want to implement tests.