Best practice for handling many individual functions

I have many small functions, each of which does one thing, for example: pingServer, checkUserValidAccount, countDistance.

You should not wrap each function in one class.

What is the best practice in C ++ for handling such various small functions?

Perhaps some class called Helpers is written, for example, NetworkHelpers?

+4
source share
3 answers

Placing them in a namespace is an option. I do not see the need for a class. The class instance is average for representing the state, but you are describing many free functions, therefore the system is stateless.

"Do not undermine every function in one class." - This is not a valid argument for deciding not to write a class. A class can have one element and one method, but if there is logic, you should write it.

If your functions and your logic require the use of a class, where your functions have the same logic, but work differently depending on the object, by all means, write a class. If your only goal is to combine functions together when their logic does not rely on the same instance of the 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, a function does not depend on anything but a parameter.

Inside the class, since it has a state, and you create an object for each server (so similar behavior, but different depending on the object), you call the function without parameters, because the object has a state.

Hope this is clear.

+6
source

Unlike some languages, C ++ does not require you to place each function in a class. If you have functions that are not part of the class, put them in a namespace.

+1
source

If I can add another good practice other than namespaces: group your functions in DLLs according to their dependencies. Avoid circular communication and create low-level libraries with as few dependencies as possible.

0
source

Source: https://habr.com/ru/post/1380143/


All Articles