While refactoring some old code I have stripped out a number of public methods that should actually of been statics as they a) don't operate on any member data or call any other member functions and b) because they might prove useful elsewhere.
This led me to think about the best way to group 'helper' functions together. The Java/C# way would be to use a class of static functions with a private constructor, e.g.:
class Helper { private: Helper() { } public: static int HelperFunc1(); static int HelperFunc2(); };
However, being C++ you could also use a namespace:
namespace Helper { int HelperFunc1(); int HelperFunc2(); }
In most cases I think I would prefer the namespace approach but I wanted to know what the pros and cons of each approach are. If used the class approach for example, would there be any overheads?
A "helper function" is a function you write because you need that particular functionality in multiple places, and because it makes the code more readable. A good example is an average function. You'd write a function named avg or similar, that takes in a list of numbers, and returns the average value from that list.
A helper method is a term used to describe some method that is reused often by other methods or parts of a program. Helper methods are typically not too complex and help shorten code for frequently used minor tasks. Using helper methods can also help to reduce error in code by having the logic in one place.
There are two types of helper functions: private functions, which you can call only inside your app, and public functions, which you can call either inside or outside your app. Private functions are commonly used in single-window apps, while public functions are commonly used in multiwindow apps.
In object-oriented programming, a helper class is used to assist in providing some functionality, which isn't the main goal of the application or class in which it is used. An instance of a helper class is called a helper object (for example, in the delegation pattern).
Overhead is not an issue, namespaces have some advantages though
You can use namespace aliasing to your advantage (debug/release, platform specific helpers, ....)
e.g. I've done stuff like
namespace LittleEndianHelper { void Function(); } namespace BigEndianHelper { void Function(); } #if powerpc namespace Helper = BigEndianHelper; #elif intel namespace Helper = LittleEndianHelper; #endif
A case where one might use class
(or struct
) over namespace
is when one needs a type, for example:
struct C { static int f() { return 33; } }; namespace N { int f() { return 9; } } template<typename T> int foo() { return T::f(); } int main() { int ret = foo<C>(); //ret += foo<N>(); // compile error: N is a namespace return ret; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With