Is using too much static bad or good? - c++

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.)

Related

Preferring non-member non-friend functions to member functions

This question title is taken from the title of item #23 in Effective C++ 3rd Edition by Scott Meyers. He uses the following code:
class WebBrowser {
public:
void clearCache();
void clearHistory();
void removeCookies();
//This is the function in question.
void clearEverything();
};
//Alternative non-member implementation of clearEverything() member function.
void clearBrowser(WebBrowser& wb) {
wb.clearCache();
wb.clearHistory();
wb.removeCookies();
};
While stating that the alternative non-member non-friend function below is better for encapsulation than the member function clearEverything(). I guess part of the idea is that there are less ways to access the internal member data for the WebBrowser if there are less member functions providing access.
If you were to accept this and make functions of this kind external, non-friend functions, where would you put them? The functions are still fairly tightly coupled to the class, but they will no longer be part of the class. Is it good practice to put them in the class's same CPP file, in another file in the library, or what?
I come from a C# background primarily, and I've never shed that yearning for everything to be part of a class, so this bewilders me a little (silly though that may sound).
Usually, you would put them in the associated namespace. This serves (somewhat) the same function as extension methods in C#.
The thing is that in C#, if you want to make some static functions, they have to be in a class, which is ridiculous because there's no OO going on at all- e.g., the Math class. In C++ you can just use the right tool for this job- a namespace.
So clearEverything is a convenience method that isn't strictly necessary. But It's up to you to decide if it's appropriate.
The philosophy here is that class definitions should be kept as minimal as possible and only provide one way to accomplish something. That reduces the complexity of your unit testing, the difficulty involved in swapping out the whole class for an alternate implementation, and the number of functions that could need to be overridden by sub-classes.
In general, you shouldn't have public member functions that only invoke a sequence of other public member functions. If you do, it could mean either: 1) you're public interface is too detailed/fine-grained or otherwise inappropriate and the functions being called should be made private, or 2) that function should really be external to class.
Car analogy: The horn is often used in conjunction w/ slamming on your brakes, but it would be silly to add a new pedal/button for that purpose of doing both at once. Combining Car.brake() and Car.honk() is a function performed by Driver. However, if a Car.leftHeadLampOn() and Car.rightHeadLampOn() were two separate public methods, it could be an example of excessively fine grained control and the designer should rethink giving Driver a single Car.lightsOn() switch.
In the browser example, I tend to agree with Scott Meyers that it should not be a member function. However, it could also be inappropriate to put it in the browser namespace. Perhaps it's better to make it a member of the thing controlling Web browser, e.g. part of a GUI event handler. MVC experts feel free to take over from here.
I do this a lot. I've always put them into the same .cpp as the other class member functions. I don't think there is any binary size overhead depending where you put them though. (unless you put it in a header :P)
If you want to go down this route the imlementation of clearEverything should be put in both the header (declaration) and implementation of the class - as they are tightly coupled and seems the best place to put them.
However I would be inclined to place them as a part of the class - as in the future you may have other things to clear or there may be a better or faster implementation to implement clearEverythingsuch as droppping a database an just recreate the tables

c++ global functions and OOP?

In C++ one can have a 'GLOBAL FUNCTION', which means it does not belong to any class. I wondered if that isn't just a violation of the basic principles of OOP?
What would be the difference with using a global function or function that is static in a class? I'm thinking the latter is more OOP oriented. But I may be wrong however...
Does it not make it harder when writing a multithreaded applicaton?
A static function inside a class is as OO as a global function inside a module. The thing is in JAVA, you don't have the choice.
In C++, you can encapsulate your global functions inside namespaces, you don't need a dummy class to do this. This way you have modularity.
So of course you can put functions outside namespaces this way you have really global functions. But that's not very different from a JAVA kitchen sink class with a bunch of static functions. It's also bad code, but can be just ok for small projects :)
Also in C++ you have a lot of choices to have "global" function that actually are linked to a class, as operator functions, that may be for instance friends of a class.
EDIT
As for multithreading, you have to worry about global variables, not functions.
C++ facilitates many programming paradigms: structured, OOP, functional.
It makes no sense to choose for an OO approach for a small (hello world-style) program.
It makes no sense to use a structured approach for a modular program.
Next to that, static class functions are just better organized than 'free' functions; on top of that, they have access to an object's private variables - better encapsulation.
Static methods are able to access private static fields on the class they're in, but that's about the only difference from global functions.
Global functions are there because C++ is roughly a superset of C, and C has global functions. C can be used for both OOP and non-OOP programming.
And, frankly, does it really make a difference whether you type std::Math::max or std::max?
Totally agree with other answers and i want to add my advice. Static functions and static methods are almost same things and abusing them can lead to poor oo design. If you want to keep your object model clean you should use static functions/methods only if:
they do not produce result that depends on state of object
they do not change state of object

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.

static class data vs. anonymous namespaces in C++

I occasionally have classes with private static data members. I'm currently debating if I should replace these with static variables in an unnamed namespace in the implementation file. Other that not being able to use these variables in inline methods, are there any other drawbacks? The advantage that I see is that is hides them completely from the users of the class.
I'm not convinced that the benefit is worth the readability impact. I generally consider something that's private to be "hidden enough."
1) There is a drawback in the form of an added restriction on binary organization. In a presentation at a C++ conference in the 1990s, Walter Bright reported achieving significant performance increases by organizing his code so that functions that called each other were in the same compilation unit. For example, if during execution Class1::method1 made far more calls to Class2 methods than to other Class1::methods, defining Class1::method1 in class2.cpp meant that Class1::method1 would be on the same code page as the methods it was calling, and thus less likely to be delayed by a page fault. This kind of refactoring is easier to undertake with class statics than with file statics.
2) One of the arguments against introducing the namespace keyword was "You can do the same thing with a class," and you will see class and struct being used as a poor-man's namespace in sources from the pre-namespace era. The convincing counter-argument was because namespaces are re-openable, and any function anywhere can make itself part of a namespace or access a foreign namespace, then there were things you could do with a namespace that you could not do with a class. This has bearing on your question because it suggests that the language committee was thinking of namespace scope as very much like class scope; this reduces the chance that there is some subtle linguistic trap in using an anonymous namespace instead of a class static.
I disagree with the other answers. Keep as much out of the class
definition as possible.
In Scott Meyers' Effective C++ 3rd edition he recommends preferring non-friend
functions to class methods. In this way the class definition is as
small as possible, the private data is accessed in as few places as
possible (encapsulated).
Following this principle further leads to the pimpl idiom. However,
balance is needed. Make sure your code is maintainable. Blindly,
following this rule would lead you to make all your private methods
file local and just pass in the needed members as parameters. This
would improve encapsulation, but destroy maintainability.
All that said, file local objects are very hard to unit test. With
some clever hacking you can access private members during unit tests.
Accessing file local objects is a bit more involved.
It not only hides them from users of the class, it hides them from you! If these variables are part of the class, they should be associated with the class in some way.
Depending on what you are going to do with them, you could consider making them static variables inside static member functions:
// header file
class A {
public:
static void func();
};
// cpp file
void A :: func() {
static int avar = 0;
// do something with avar
}
I guess it boils down to whether these variables have some actual meaning in the context of the class (e.g., pointer to some common memory used by all objects) or just some temporary data you need to pass around between methods and would rather not clutter the class with. In the latter case I would definitely go with the unnamed namespace. In the former, I'd say it's a matter of personal taste.
I agree partly with Greg, in that unnamed namespace members aren't any more encapsulated than private data. The point of encapsulation, after all, is to hide implementation details from other modules, not from other programmers. Nevertheless, I do think there are some cases where this is a useful technique.
Consider a class like the following:
class Foo {
public:
...
private:
static Bar helper;
};
In this case, any module that wants to use Foo must also know the definition of Bar even though that definition is of no relevance what-so-ever. These sort of header dependencies lead to more frequent and lengthier rebuilds. Moving the definition of helper to an unnamed namespace in Foo.cpp is a great way to break that dependency.
I also disagree strongly with the notion that unnamed namespaces are somehow less readable or less maintainable than static data members. Stripping irrelevant information from your header only makes it more concise.

Implementation in global functions, or in a class wrapped by global functions

I have to implement a set of 60 functions, according to the predefined signatures. They must be global functions, and not some class's member functions. When I implement them, I use a set of nicely done classes provided by 3rd party.
My implementation of most functions is quite short, about 5-10 lines, and deals mostly with different accesses to that 3rd party classes. For some more complicated functions I created a couple of new classes that deal with all the complicated stuff, and I use them in the functions too. All the state information is stored in the static members of my and 3rd party's classes, so I don't have to create global variables.
Question: Would it be better if I implement one big class with 60 member functions, and do all the implementation (that is now in the global functions) there? And each of the functions that I have to write will just call to the corresponding member function in the class.
All the state information is stored in the static members of my and 3rd party's classes, so I don't have to create global variables.
That is the keypoint. No, they should definitely not be put into classes. Classes are made to be used for creating objects. In your situation, you would use them just as a scope, for the data and functions. But this is what namespaces already solve better:
namespace stuff {
... 60 functions ...
namespace baz {
... if you want, you can have nested namespaces, to ...
... categorize the functions ...
}
namespace data {
... you can put data into an extra namespace if you want ...
}
}
Creating classes that consist purely only of static members is a bad idea.
Do the users of your code really need this big class?
If yes, implement it.
If no, don't waste your time on implementing it and don't waste the time of others mandated to test it or trying to understand what is the exact role of this class beyond the OOP look.
litb is probably correct. The only reason that you would even consider wrapping a class around a bunch of free functions is if you need to attach some of your own data for use in your wrappers. The only thing that pops into my head is if need a handle to a log file or something similar in the wrappers.
On a related note, fight the temptation of using namespace stuff;! Always refer to the functions using namespace qualification:
#include <stuff.h>
void some_function() {
stuff::function_wrapper();
}
instead of:
#include <stuff.h>
using namespace stuff;
void some_function() {
function_wrapper();
}
The benefit is that if you ever need to convert the namespace to a class full of static methods, you can do it easily.
I think that the "one class one responsibility" rule should guide you here. The 60 functions can probably be divided into different responsibilities, and each of those deserves a class. This will also give a more OO interface to clients of the API that are not constrained by the need of global functions.