Are static functions an acceptable practice for some things in C ++?

Sometimes for some things, such as writing a string to the console, it seems that all objects should be globally accessible. Sort of:

writeError("UNHANDLED EXCEPTION",someData); 

Also, things like mathematical functions are also felt. But how do you draw a line when you do such things, becomes bad practice?

+4
source share
3 answers

Some people draw a line at the point where a non-member function should be a friend one of their arguments, so they use many free functions.

Some people draw a line at a point where a non-member function can reasonably be a member function of one of its arguments, even if it does not actually use the internal elements of the class. They have slightly less free features.

It’s usually best not to think of it as “becoming bad practice” - not all C ++ designs are “correctly” object oriented. If your task is best accomplished by other means than OOP, then using OOP itself is "bad practice." The argument about how to best develop your code can go on indefinitely in any language, but C ++ does not make much effort to direct you to writing classes.

See also:

Effective C ++ element. 23 Preferred member function for member functions

+10
source

These kind of global APIs are just great.

The best practice these days is to combine them in a namespace:

 namespace LOGGING { void writeError(message, ...); } 

Creating something static in C ++ is not the same as doing something static in Java. In C ++, a static function is visible only from this compilation unit (.cpp file). This does not make it a global non-class function.

The static member function in C ++, however, is the same in Java - it allows it to be called because of the object object class class :: method (params) instead of classObject.method (params).

+6
source

There are two questions here:

Are static functions an acceptable practice for certain things in C ++?

Yes, some things can only be archived using functions. For example, registration for reassignment of callbacks.

Also things like math functions feel fine too. But how do you draw a line when doing this kind of thing becomes bad practice?

In addition, class operators can be functions (for example, operator +, taking two operands or a stream operator. How to draw a line? I assume that there are enough bad things to determine what is bad and what is good. Get experience, enough experience, and you I can advise you to try your unit code completely. Having long and complex unit tests or not being able to easily unit test, something is usually a sign of a problem.

+1
source

All Articles