Best practice of handling many single functions - c++

I have many small functions which every is doing a single thing like for example:
pingServer, checkUserValidAccount, countDistance.
It is not worth of wrapping every function into single class.
What is the best practice in c++ to handle such a different many small functions?
Maybe writing some class called Helpers like for example NetworkHelpers?

Placing them in a namespace is an option. I don't see the need for a class. An instance of a class is mean to represent a state, but you're describing a bunch of free functions, so a stateless system.
"It is not worth of wraping every function into single class." - this is not a valid argument for making the decision not to write a class. A class can have a single member and a single method, but if there is logic behind it, you should write it.
If your functions and your logic mandates the use of a class, where your functions have the same logic but operate differently depending on the object, by all means, write a class. If your sole purpose is to group the functions together, when their logic doesn't really rely on the same instance of a class, group them in a namespace.
An example based on your question:
namespace NetworkHelpers
{
//free function, use a namespace
bool pingServer(std::string hostname);
}
//alternative, where the object has a state:
class ServerConnection
{
std::string _hostname;
public:
NetworkHelpersClass(std::string hostname)
{
_hostname = hostname;
}
bool pingServer()
{
return NetworkHelpersNamespace::pingServer(_hostname);
}
};
As you can see, inside the namespace, the function doesn't depend on anything other than the parameter.
Inside the class, since it has a state and you create an object for each server (so similar behavior, yet different depending on the object), you call the function with no parameters as the object has a state.
I hope this makes it clear.

Unlike some languages, C++ does not require that you put every function in a class. If you have functions that don't belong in a class, put them in a namespace.

If I may add another best practice other than namespaces: group your functions in DLLs minding their dependencies.
Avoid circular linking and create low-level libraries with the smallest number of dependencies as possible.

Related

Using C++ Classes to handle commonly used parameters

My team works on an HTTP web server in C++. The codebase has aged over time, and has a widespread problem of 12+ parameters being passed to every function.
A fake example: We need to build a Car, but in order to do that, we have the following function:
MaybeBuildCar(engine_params, steering_params, interior_params, fuel_params, available_inventory, parts, &debug);
Someone on our team has proposed that we create a wrapper CarBuilder class whose constructor takes in the params and "stateful" objects like available_inventory, then has a separate function for BuildCar as follows:
CarBuilder car_builder(engine_params, steering_params, interior_params, fuel_params, available_inventory, &debug);
auto car = car_builder.BuildCar(parts);
Personally, I don't see much value in having a class with a single public function that is always called. We'll always need these parameters, and we'll always need the parts, so this just adds more steps to build the car. It could even add confusion, as now a user of CarBuilder must know to both construct it and call BuildCar.
Admittedly, this simplifies our helper functions within car_builder.cc, as they also require passing these params, but to me that's misusing what a class is for: maintaining state.
Is creating this CarBuilder a misuse of the class, or is simply cleaning up function signatures a valid use? Does anyone have any suggestions on how to tackle this problem?
Minimizing function parameters can be a blessing for heavily used functions in a performance-sensitive environment:
If you pass 6 references to a function, that is 6 pointer copies pushed to the stack;
If you pass a single CarBuilder, it is one "reference-that-contains-6-other-references".
It depends on your situation.
you could define a class that contains all parameters and in each function just passed this object.
struct CarComponent
{
public:
EngineParams engine_params;
SteeringParams steering_params;
InteriorParams interior_params;
FuelParams fuel_params;
AvailableInventory available_inventory
};
MaybeBuildCar(car_component);
other_function(car_component);
Advantage:
Function's signature is decoupled from changing members of the struct (CarComponent). easy to change.
Refactor all the parameters in each function with a specific object. it prevents repetition and it becomes easier to read the code.

Better way to design code structure of many singletons

I have many classes designed like below and they have to be accessible everywhere at any time (also just as a single instance). Currently Ive done that using a namespace which stores pointer to all classes. Is there any better way to solve/design such problems/structures?
// AbcManager.h
class AbcManager
{
public:
void printTest();
private:
char text[] = "Hello world";
}
// ManagerNamespace.h
namespace Manager
{
AbcManager* abc;
}
// somewhere.h
{
Manager::abc->printTest();
}
Two requisites are demanded:
SRP
Readability
After giving some careful thought it is clear that SRP is not an issue, since, as OP stated:
they have to be accessible everywhere at any time
Which means there is absolutely no need to have separate objects. If the namespace stores all the pointers, but the initialization of different objects is done stack-wise? At any time, some might be missing, pointing to null. Which only leaves the following trivial possibilities:
With no information hiding: Nested namespaces wrapping static functions and variables.
With information hiding: Single 'big' singleton manager class. For additional readability, use prefixes in the name of variables and member functions.
Keep what you already have
I would recommend making the distinction between a singleton (object that can have only a single instance) and a normal object which gets instantiated only once by your code (the latter is not a singleton).
Would a template be a good fit, considering you have "many classes designed like below". Just instantiate each template with the type/nontype parameter you need. Not sure if this is what you're asking though.

Class with no data members in C++

This may not be a question specific to C++ and more to do with Object oriented programming. I am new to this and I am doubtful of my design. I have a class Parser that basically implements many functions dealing parsing expressions, conversion from infix to postfix etc. I use these Parser functions in the main function. I realized that I do not need any data members for this class. Hence, I do not really need an object of this class. Hence, I ended up making every function static in the class. Is there something strange about this design. Should I have this as an interface instead? Any suggestions?
You want a parser and you know what you want it to do for you - this is in effect, your "interface".
Your current implementation of the parser doesn't need any member variables - therefore, to implement your interface, you don't need a class. So yes, do away with your static methods. Like Kevin says, using a namespace with plain old functions (non-static) is a great idea.
If you feel you will need to add a new parser that WILL need to maintain internal state, then you probably want to define an interface in (1) - a plain old publicly visible header file with function declarations inside a namespace of your choice is enough.
A class with nothing but static functions seems pretty indistinguishable from a namespace to me. So, why not just use a namespace?
The way to decide for this question is on how will the functions be used?
1) If all the functions are used in one file and do not need to be exported anywhere, then definitely use static functions. Why? Because you can just type them directly into the body of the class in the .cpp file and you do not have to worry about maintaining declarations and keeping parameters aligned. Because when a C++ class is parsed all the code inside each function defined inside the class body is skipped and then parsed once all the classes members have been declared, so the functions can all see each other and are in a better name situation.The compiler will also inline a lot of the smaller functions if you declare them directly in the class like that.
2) If the functions need to be used from outside the current .cpp file, then use normal functions. Because later they can be used from anywhere else and exporting them by name is easier.
It is common to make utility functions static, so, if the functions of your Parser class do not rely on each other, you totally can made them static. If they rely on each other, and it may be possible that the same functions can be done another way, you should consider to use an interface

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.

Is using too much static bad or good?

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