fen
fen

Reputation: 10115

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?

Upvotes: 1

Views: 502

Answers (2)

lontivero
lontivero

Reputation: 5275

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.

Upvotes: 1

MSalters
MSalters

Reputation: 179799

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.

Upvotes: 2

Related Questions