Which is best for a repeating piece of code? - c++

I have a class with two member functions that share a piece of code:
void A::First()
{
firstFunctionEpilogue();
sharedPart();
}
void A::Second()
{
secondFunctionEpilogue();
sharedPart();
}
Currently firstFunctionEpilogue(), secondFunctionEpilogue() and sharedPart() are not function calls but just pieces of code, sharedPart() code being duplicated. I want to get rid of the duplication.
The shared piece of code doesn't need access to any members of the class. So I can implement it as any of the three:
a static member function,
a const non-static member function or
a local function.
Which variant is better and why?

If your function accesses state but does not change it then use a const member function.
Your case:
If it your function 1) doesn't need access to any member of the code, and 2) is related to that class, then make it a static function of your class.
That way it is clear that it is not modifying state, nor based on the state of the object.
An extra case you didn't mention:
There is another thing you can do too. And that is to make your SharedPart take in a member function pointer and to call it and then process it's main body. If you have a lot of First(), Second(), Third(), Fourth(), ... such functions then this can lead to less code duplication. That way you don't need to keep calling SharedPart(); at the end of each member function, and you can re-use First(), Second(), THird(), ... without calling the SharedPart() of the code.

I'd say:
It probably doesn't matter, so it's not so much "best practice" as "just don't do anything crazy".
If the class and all its members are defined in its header, then a private static member function is probably best, since it clearly indicates "not for clients". But there are ways to do this for a non-member function: don't document it, put in a comment "not for clients", and stick the whole thing in namespace beware_of_the_leopard.
If the class member functions are defined in a .cpp file, then little helper functions like this are best as free functions in the .cpp file. Either static, or in an anonymous namespace.

Or it could be in a different class.
Or, if it's a member, it could be virtual.
There are a lot of decisions, and I wouldn't stress out about it too much. Generally, I opt for a const non-static member function as a default unless I have a good reason not to do it that way.
Prefer static if clients need to call it without having an instance
Prefer local functions if you don't want to clutter the .h file or you want it completely hidden in the .c

Make it a non-member function
The shared piece of code doesn't need access to any members of the class.
As a general rule, if a piece of code doesn't need access to any members of the class don't make it a member function! Try to encapsulate your classes as much as possible.
I'd suggest doing a non-member function in a separate namespace that would call the public methods and then call the function you made for the shared code.
Here is an example of what I mean :
namepsace Astuff{
class A{...};
void sharedPart(){...};
void first(const A& a);
void second(const A& a);
}
void Astuff::first(const A& a){
a.first();
sharedPart();
}

a static member function, a const
non-static member function or a local
function.
Generally, it should be a member function of another class, or at least non-static member of the class itself.
If this function is only called from instance members of a class - probably its logical meaning requires an instance, even if syntax does not. Can anything except this object provide meaningful parameters or make use of the result?
Unless it makes sense to call this function from outside of the object instance, it shouldn't be static. Unless it makes sense to call this function without accessing your class at all, it shouldn't be local.
Borrowing examples from Brian's comment:
if this function changes global state, it should be member of a class of global state;
if this function writes to file, it should be member of a class of file format;
if it's refreshing screen, it should be member of... etc
Even if it's a plain arithmetic expression, it may be useful to make it a member (static or not) of some ArithmeticsForSpecificPurpose class.

Make it a non-member non-friend function. Scott Meyer's has a great explanation for this here (and also Item 23 of Effective C++ 3rd Edition).

As a rule of thumb "try to keep it as local as possible but as visible as necessary".
If all code calling the function resides in the same implementation file, this means keeping it local to the implementation file.
If you'd make it a private static method of your class, it would not be callable by implementaions including your class, but it would still be visible to them. So every time you change the semantics of that method, all implementaions including your calls will have to recompile - which is quite a burden, since from their point of view, they don't even need to know those sementics.
Thus, in order to minimize unnecessary dependencies, you would want to make it a static global function.
However, if you should ever find yourself repeating this global function in mulitple implementation files, it would be time to move the function into a seperate header/implementaion file pair, so that all callers can include it.
Whether you place that function into a namespace, at global scope, or as a static function in a class is really up to taste.
On a final note, if you go for the global static function, there's a "more c++ like" version: anonymous namespaces. It has the nice property that it can actually store state and also prevents users for being able to even forward declare any of its functions.
// in your .cpp file
namespace /*anonymous*/
{
void foo()
{
// your code here
}
};
void MyClass::FooUser1() { foo(); }
void MyClass::FooUser2() { foo(); }

Related

Free functions vs singleton vs static class members [duplicate]

I already read a lot of posts and articles all over the net, but I couldn't find a definite answer about this.
I have some functions with similar purposes that I want to have out of the global scope. Some of them need to be public, others should be private (because they are only helper functions for the "public" ones).
Additionally, I don't have only functions, but also variables. They are only needed by the "private" helper functions and should be private, too.
Now there are the three ways:
making a class with everything being static (contra: potential "Cannot call member function without object" - not everything needs to be static)
making a singleton class (contra: I WILL need the object)
making a namespace (no private keyword - why should I put it in a namespace at all, then?)
What would be the way to take for me? Possible way of combining some of these ways?
I thought of something like:
making a singleton, the static functions use the helper function of the singleton object (is this possible? I'm still within the class, but accessing an object of it's type)
constructor called at programm start, initializes everything (-> making sure the statics can access the functions from the singleton object)
access the public functions only through MyClass::PublicStaticFunction()
Thanks.
As noted, using global variables is generally bad engineering practice, unless absolutely needed of course (mapping hardware for example, but that doesn't happen THAT often).
Stashing everything in a class is something you would do in a Java-like language, but in C++ you don't have to, and in fact using namespaces here is a superior alternative, if only:
because people won't suddenly build instances of your objects: to what end ?
because no introspection information (RTTI) is generated for namespaces
Here is a typical implementation:
// foo.h
#ifndef MYPROJECT_FOO_H_INCLUDED
#define MYPROJECT_FOO_H_INCLUDED
namespace myproject {
void foo();
void foomore();
}
#endif // MYPROJECT_FOO_H_INCLUDED
// foo.cpp
#include "myproject/foo.h"
namespace myproject {
namespace {
typedef XXXX MyHelperType;
void bar(MyHelperType& helper);
} // anonymous
void foo() {
MyHelperType helper = /**/;
bar(helper);
}
void foomore() {
MyHelperType helper = /**/;
bar(helper);
bar(helper);
}
} // myproject
The anonymous namespace neatly tucked in a source file is an enhanced private section: not only the client cannot use what's inside, but he does not even see it at all (since it's in the source file) and thus do not depend on it (which has definite ABI and compile-time advantages!)
Don't make it a singleton
For public helper functions that don't directly depend on these variables, make them non-member functions. There's nothing gained by putting them in a class.
For the rest, put it in a class as normal non-static members. If you need a single globally accessible instance of the class, then create one (but don't make it a singleton, just a global).
Otherwise, instantiate it when needed.
The classic C way of doing this, which seems to be what you want, is to put the public function declarations in a header file, and all the implementation in source file, making the variables and non-public functions static. Otherwise just implement it as a class - I think you are making a bit of a mountain out of a molehill here.
What about using a keyword static at global scope (making stuff local to the file) as a privacy substitute?
From your description it looks like you have methods and data that interact with each other here, in other words it sounds to me like you actually want a non-singleton class to maintain the state and offer operations upon that state. Expose your public functions as the interface and keep everything else private.
Then you can create instance(s) as needed, you don't have to worry about init order or threading issues (if you have one per thread), and only clients that need access will have an object to operate upon. If you really need just one of these for the entire program you could get away say a global pointer that's set in main or possibly an instance method, but those come with their own sets of problems.
Remember that the singleton instance of a singleton class is a valid instance, so it is perfectly able to be the recipient of nonstatic member functions. If you expose your singleton factory as a static function then have all of your public functionality as public nonstatic member functions and your private functionality as private nonstatic member functions, anyone that can get at the class can access the public functionality by simply invoking the singleton factory function.
You don't describe whether all of the functionality you're trying to wrap up is as related as to justify being in the same class, but if it is, this approach might work.
If you take a "C-like" approach and just use top-level functions, you can make them private by declaring them in the .cpp file rather than the publicly-included .h file. You should also make them static (or use an anonymous namespace) if you take that approach.

Private C++ member function vs C function

I have a C++ class, and in one of the member functions there is a duplicate section of code. So I've extracted this out into a function, however only this member function will call this new function. At the moment it's just a c function defined in the cpp file and not declared anyway else.
Is there any advantage to making this a private C++ member function, the code in the function itself doesn't use any instead variables of the class.
Well, if it's any addition to the argument, the newest CppCoreGuidelines say that you should "C.5: Place helper functions in the same namespace as the class they support". So they shouldn't be a part of the actual class, but part of the namespace that they reside in.
If you add it to the class then it becomes part of the classes signature.
As such making changes to the function signature would change the class signature. Given it would be a private function it is not likely that you would gain much by exposing it in that way.
If though it needs to access internals of the class then having as part of the class would likely simplify its implementation.
If it does not need to access the internals you can make add it to an anonymous namespace within the cpp file. That way the function symbol will not be exposed anywhere that is is not needed.
(Sort of an extended comment)
You've declared a free function in the .cpp file.
This a good design decision as other answers point out. The clearest thing you can have is a method only visible from that .cpp file that can't see or change state. I might be tempted to put it in the same namespace as the class as per the CppCoreGuidelines.
Equivilently, you could have declared a private static member function in your header file. This is static in the C#/Java sense rather than in either of the C senses (C++ has all of these meanings). However, I don't see the benifit as the only thing you gain is unnecessary recompilations.
Yes. Putting the function in class defines scope and context of it. This makes maintenance easier and also will allow you to extend its functionality in the future without significant code rewriting. Actually, in such cases I usually prefer making the function static in the class, i.e., meeting somewhere in the middle.

Is there any way to change the scope of a callback without changing the paramaters?

I am using SDL2_mixer library, but I believe that the question should hold for the general case also.
Currently, a function that I would like to use, Mix_HookMusicFinished(void (*music_finished)(void)) has a set callback to the global scope for a C style function. However, I would like to have that callback be set to a member function within my own class void CMusic::musicFinished() without having the need for a function in global scope.
Is there anyway to do this? Something like Mix_HookMusicFinished(musicFinished) would be great, but that directly has an error of argument of type "void (CMusic::*)()" is incompatible with parameter of type "void (*)()"
You need to make a "wrapper" function. However, the problem here is that you also need to be able to find the CMusic object that you want to "finish" - this is really what the crux of
argument of type ... is incompatible with ...
is all about. Since there is no way to pass a parameter to the musicFinished object, you will need some other way of "finding" the CMusic object.
If we assume there is a way to do that, then something like this would work:
class CMusic
{
...
public:
...
static void musicFinishedWrapper();
void musicFinished();
...
};
void CMusic::musicFinishedWrapper()
{
CMusic* music = getTheMusicSomehow(); // No idea how you do this - depends on your code.
music->musicFinished();
}
The reason you have to have a CMusic object is that your musicFinished expects a (hidden) this pointer argument - which is the value in music in my little function.
You could move musicFinished to your CMusic class and declare it as a static class method. static class methods aren't called on an object; they therefore don't have an implicit argument to specify the value of the this pointer, and they therefore can have the same signature as freestanding functions. You additionally can make it private to prevent anything but CMusic from using it.
However, since your musicFinished method currently works as a freestanding function and therefore probably doesn't need access to CMusic's protected or private members, and since your efforts to limit its scope presumably means that you don't want other things to call it, I personally would leave your musicFinished function as freestanding but declare it as static (or move it to an anonymous namespace, if you prefer) within the CMusic source (.cpp or .cc) file. Doing so would restrict its scope to the source file (the "compilation unit"). An advantage over a private, static class method is that it does not need to be exposed at all in a header file, so it is in some sense more private.

Hiding free functions

Lets say I have a bunch of free functions, within a particular namespace, which are covered by unit-tests. And lets say I see some common functionality that can be moved out into a separate free function. What can I do such that this new function becomes hidden? In other words, this function should only be used by the aforementioned free functions and not elsewhere. Should I added it to a namespace under the free functions' namespace. If so, what should I call the namespace - is there a naming convention?
I should also point out that this new function is not unit tested since it is used internally by other functions that are unit-tested. Perhaps I'm being lazy and the solution to this question is that I simply unit-test this function also and then people can use it if they want.
You can hide it: make it a private static member function of a class, and then explicitly friend each of your inline functions. The implementation could be in- or out-of-line, access control will still work.
Unless you need to restrict access though, I'd follow the Boost convention and just put it in a nested namespace called detail (or something similar).
This is just intended to document that it is an implementation detail, rather than a stable public interface (and to avoid polluting the namespace, of course).
This also avoids having to explicitly list each free function as a friend.
You could have the helper function as a static function in the private section of a class and then only friend the functions that are allowed to use it.
class Foo
{
static int helper() {return 0;}
friend void baz();
};
void baz()
{
Foo::helper(); //compiles
}
void buz()
{
Foo::helper(); //doesn't compile
}

should C++ class "helper functions" be members, free, or anon-namespace free?

So, I have a class. It's a useful class. I like a lot. Let's call it MyUsefulClass.
MyUsefulClass has a public method. Let's call it processUsefulData(std::vector<int>&).
Now suppose processUsefulData really does two things and I want to refactor it from this:
std::vector<int> MyUsefulClass::processUsefulData(std::vector<int>& data)
{
for (/*...*/)
{
for (/*...*/)
{
// a bunch of statements...
}
}
for (/*...*/)
{
for (/*...*/)
{
// a bunch of other statements...
}
}
return data;
}
Now, I want to split these responsibilities and rewrite the code as
std::vector<int> MyUsefulClass::processUsefulData(std::vector<int>& data)
{
doProcessA(data, dataMember_);
doProcessB(data, otherDataMember_);
return data;
}
So, I don't know if I should make the two helper functions free functions or member functions, and when each would be appropriate. I also don't know if it's better to make them in an anonymous namespace or not. Does anyone know good times to do this?
I generally make helper routines "free" routines in an anonomous namespace if possible. That way I don't complicate the interface (off in the *.h file) with stuff clients don't need to worry about.
However, you have to be careful that you don't introduce non-reentrancy by doing that. For instance, by modifying global data objects or static locals rather than class members. If you need to do that, you are better off making it a proper class member.
Free function / member function
I would make them free functions is possible (they do not need access to the internals of the class). If they work on a set of attributes or need access to other members then make it a member function.
Access
If the code only has sense in this scope, and will not be used from other code then make them private: private if it is a member, or implemented in an unnamed namespace if it is a free function.
If other code will benefit from using the code then publish it in the interface. That means making it protected if it is a member or having the free function accessible through a header in a named namespace (or global namespace).
I usually make them protected or private member functions. It would depend on whether you plan on deriving the class and overriding the functions.
If they are common enough functions that they are used in other classes, move them to static functions contained in a common class or a separate object that your class uses.
Always prefer free functions over member ones.
See my answer here to know why.
The fact that you mention free functions leads me to believe that the 'bunch of other statements' do not require access to class data. If so, make them free. This reduces complexity of your class header, plus free functions are easier to use in the standard algorithms (maybe std::for_each since you're working with vectors anyway?).
Think about the scope. Are those functions going to be used in another class, or elsewhere? Should they be publically call-able?
It seems like they should be private member functions to me, but it all depends on your overall scoping structure.
Member functions certainly if the original function made sense as a member function.
Private/protected IMHO depends on how their functionality is used: if the original function's operation is still required and the refactor is solely to make the code cleaner then make them protected or private and call them from the regular function. You get the refactor but keep the class's public interface intact that way.