Convert all functions to classes

I read the book Refactoring: Improving the Design of Existing Code from Fowler, which says that instead of calling a function call, instead of calling functions, the same name classes and call constructors of this class are used.

My question is a good idea to convert all functions (more or less, except very trivial) into objects so that the code becomes more modular?

Thanks,

+4
source share
4 answers

Expand the bit in my previous comment:

In C ++ there is absolutely no reason to turn all functions into classes, some processing objects. Functions work well when you just need to calculate and return a value.

However , if you have a large function that creates an internal state and uses it in several places during processing, or (gasp!) Stores some state in global variables, this function may be a class in disguise. In this case, it might be a good idea to maintain state in a class object with several smaller member functions that do their job in this general state.

On the other hand, a function that only calculates a value from its parameters does not improve by placing it in a class.

+5
source

No, why? If you have functionality that is logically a function (stateless calculation), and there is no good reason to implement it as a class, then just implement it as a function.

The advice "replace function calls with the same name classes and call constructors of this class instead of the original function call" is incorrect: how can you replace

int y = f(x); 

through class f and calling its constructor? The constructor has no return value! The only way to get this to work is to overload operator() on class f so you can use one of

 int y = f(x)(); int y = f()(x); 

both of them are meaningless. (In addition, you will need to remember which one you need for each function object you define.)

There must be something you don’t tell us about.

+2
source

In my opinion, converting functions to classes is completely pointless. Why would you want to do that?

When you convert your functions into objects, you don’t type anything. A method call is actually the same simple function call, only with the this argument hidden. In your case, this argument will be redundant, since your object has no state.

The only reason I can think of converting functions to objects is to pass functions as objects to other functions, but for this purpose we have pointers to functions or boost :: function or C ++ 0x lambdas.

+1
source

Finally, no! It makes no sense to convert any function to a class.

The class is going to manage some state of the object and hide information, the functions are global and mostly stateless. Many loss classes make software inefficient and unbearable.

0
source

All Articles