I am looking for an article or documentation that explains why a free static function is better than a private member function, when the given function does not modify or read the private members of the class. To my point of view the advantages are :
Less dependencies
Better encapsulation (for "mammoth" classes, it helps to know that at least those function calls do not modify the members)
I am certain someone has already written something better than what I can do.
Free static functions are passe. One would use a function in the anonymous namespace instead.
They are slightly more maintainable -- since they can't access private members, they are robust against changes to implementation details. A static member function could also be independent of implementation details, but you don't have the compiler verifying that.
If you are specifically looking for an article you should read "Item 23: Prefer non-member non-friend functions to member functions" in Effective C++ by Scott Meyers. I would suggest that this book is essential reading for all serious C++ programmers.
The basic premise for this topic is that if you can implement a free function using existing interface methods of a class then you should as this actually simplifies the class. That is, the less code that can see the internals of the class the more encapsulated it is. Adding more bloat actually decreases encapsulation.
You seem to be misusing some words so I'll attempt to clarify
class myclass {
private:
int data;
void func1(); // private mutator function
void func2() const; // private accessor function
static void func3(); // private static function
public:
int moredata;
void func4(); // public mutator function
void func5() const; // public accessor function
static void func6(); // public static function
}
void func7(myclass); // free function
static void func8(myclass); // static function can't be accessed outside file.
Generally, operator overloads tend to free functions so that way they can be found during lookup if a conversion is needed.
Private functions are used when no outside functions or classes will call those functions.
Static functions are used when they do not read or write to a myclass, but are an integeral part of the concept of the class.
Constant functions can be used on const objects, and do not modify the class.
encapsulation means combining relevant data and functions. So it's irrelevant here.
If a function doesn't change member variables it is marked as const, but depending on the context it can still happily belong to a class instead of being forced to be a lonely free static function.
Personally (this can be debated) I believe that you should put together all relevant functions into a single class or AT THE VERY LEAST a namespace instead of leaving them all alone.
Though from java, from design pov this is a valid example: http://download.oracle.com/javase/1.5.0/docs/api/java/util/Arrays.html, http://download.oracle.com/javase/1.5.0/docs/api/java/util/Collections.html
Related
I am reading some of the Epic Games UnrealEngine4 source code and see couple of practices which make me wonder if I miss some of essential C++ magic.
static inline member methods in class declaration.Here #dividebyzero user actually sheds very important info regarding the effect of using static inline,at least with GCC compiler - inline placement similar to how MACRO functions behave.
Another interesting practice I can see is how UE4 creates interfaces for inheritance.Here is example based on how OpenGL backend module in UE4 looks like:
class FOpenGLBase
{
public:
static FORCEINLINE void UnmapBufferRange(GLenum Type, uint32 InOffset, uint32 InSize) UGL_REQUIRED_VOID
};
Where UGL_REQURED_VOID is replaced with default function body,which reports "unimplemented" method error if called on this base class.
Next come inheritance of the above class:
struct FOpenGL3 : public FOpenGLBase
{
static FORCEINLINE void UnmapBuffer(GLenum Type)
{
glUnmapBuffer(Type);
}
static FORCEINLINE void UnmapBufferRange(GLenum Type, uint32 InOffset, uint32 InSize)
{
UnmapBuffer(Type);
}
};
I even didn't know it was possible for a struct to inherit from class and vice -versa.
I understand that static + inline makes it possible to generate unique function body per function call,which makes it possible to put different body but with same signature in subclass's declaration.
But then I also wonder why one needs virtual inheritance for small methods if it is possible to override static inline methods in subclass just like this?
Why such an approach is not common? (at least from my experience I find it uncommon)
PS: I wasn't sure if this question format is ok for SO or should be rather put in CodeReview site.
First of all, the post you refer to seems to be about static inline functions in the namespace scope. Your example has them in a class scope. There's a very big difference between these two scopes.
In class scope, the static keyword makes the method callable on the class, instead of on an instance. So in this scope, there's a very real difference between static, static inline and just inline.
Next, static methods in class scopes have nothing to do with inheritance, exactly because static members are part of the class rather than instances. Inheritance is only relevant for instances. To make this clear, consider how you would call UnmapBufferRange on either FOpenGLBase or FOpenGL3:
FOpenGLBase::UnmapBufferRange(..); // Call the FOpenGLBase version
FOpenGL3::UnmapBufferRange(..); // Call the FOpenGL3 version
There's no inheritance because you couldn't even override it - you simply redefine it for another class. This effectively hides it, so it looks like inheritance but it's not the same!
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
}
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(); }
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.
I like to use static functions in C++ as a way to categorize them, like C# does.
Console::WriteLine("hello")
Is this good or bad? If the functions are used often I guess it doesn't matter, but if not do they put pressure on memory?
What about static const?
but is it good or bad
The first adjective that comes to mind is "unnecessary". C++ has free functions and namespaces, so why would you need to make them static functions in a class?
The use of static methods in uninstantiable classes in C# and Java is a workaround because those languages don't have free functions (that is, functions that reside directly in the namespace, rather than as part of a class). C++ doesn't have that flaw. Just use a namespace.
I'm all for using static functions. These just make sense especially when organized into modules (static class in C#).
However, the moment those functions need some kind of external (non compile-time const) data, then that function should be made an instance method and encapsulated along with its data into a class.
In a nutshell: static functions ok, static data bad.
Those who say static functions can be replaced by namespaces are wrong, here is a simple example:
class X
{
public:
static void f1 ()
{
...
f2 ();
}
private:
static void f2 () {}
};
As you can see, public static function f1 calls another static, but private function f2.
This is not just a collection of functions, but a smart collection with its own encapsulated methods. Namespaces would not give us this functionality.
Many people use the "singleton" pattern, just because it is a common practice, but in many cases you need a class with several static methods and just one static data member. In this case there is no need for a singleton at all. Also calling the method instance() is slower than just accessing the static functions/members directly.
Use namespaces to make a collection of functions:
namespace Console {
void WriteLine(...) // ...
}
As for memory, functions use the same amount outside a function, as a static member function or in a namespace. That is: no memory other that the code itself.
One specific reason static data is bad, is that C++ makes no guarantees about initialization order of static objects in different translation units. In practice this can cause problems when one object depends on another in a different translation unit. Scott Meyers discusses this in Item 26 of his book More Effective C++.
Agree with Frank here, there's not a problem with static (global) functions (of course providing they are organised).. The problems only start to really creep in when people think "oh I will just make the scope on this bit of data a little wider".. Slippery slope :)
To put it really into perspective.. Functional Programming ;)
The problem with static functions is that they can lead to a design that breaks encapsulation. For example, if you find yourself writing something like:
public class TotalManager
{
public double getTotal(Hamburger burger)
{
return burger.getPrice() + burget.getTax();
}
}
...then you might need to rethink your design. Static functions often require you to use setters and getters which clutter a Class's API and makes things more complicated in general. In my example, it might be better to remove Hamburger's getters and just move the getTotal() class into Hamburger itself.
I tend to make classes that consist of static functions, but some say the "right way" to do this is usually to use namespaces instead. (I developed my habits before C++ had namespaces.)
BTW, if you have a class that consists only of static data and functions, you should declare the constructor to be private, so nobody tries to instantiate it. (This is one of the reasons some argue to use namespaces rather than classes.)
For organization, use namespaces as already stated.
For global data I like to use the singleton pattern because it helps with the problem of the unknown initialization order of static objects. In other words, if you use the object as a singleton it is guaranteed to be initialized when its used.
Also be sure that your static functions are stateless so that they are thread safe.
I usually only use statics in conjunction with the friend system.
For example, I have a class which uses a lot of (inlined) internal helper functions to calculate stuff, including operations on private data.
This, of course, increases the number of functions the class interface has.
To get rid of that, I declare a helper class in the original classes .cpp file (and thus unseen to the outside world), make it a friend of the original class, and then move the old helper functions into static (inline) member functions of the helper class, passing the old class per reference in addition to the old parameters.
This keeps the interface slim and doesn't require a big listing of free friend functions.
Inlining also works nicely, so I'm not completely against static.
(I avoid it as much as I can, but using it like this, I like to do.)