Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting all functions into classes

I was reading the book Refactoring: Improving the Design of Existing Code by Fowler, where it says to replace function calls with same names classes and call constructors of that class in place of original function call.

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

Thanks,

like image 938
PTS Avatar asked Feb 24 '23 11:02

PTS


2 Answers

Expanding a bit on my earlier comment:

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

However, if you have a large function that creates an internal state and uses that in several places during its processing, or (gasp!) stores some state in global variables, that function might be a class in disguise. In that case it can be a good idea to store the state in a class object with several smaller member functions doing their work on that common state.

On the other hand, a function that only computes a value from its parameters is not improved by putting it into a class.

like image 193
Bo Persson Avatar answered Mar 03 '23 23:03

Bo Persson


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

The advice to "replace function calls with same names classes and call constructors of that class in place of original function call" is plain wrong: how can you replace

int y = f(x);

by a class f and a call to its constructor? A constructor doesn't have a return value! The only way to get this to work is to overload operator() on the class f so you can use one of

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

both of which are pointless. (Also, you'd have to remember which one of these you need for every function object you define.)

There must be something you're not telling us.

like image 21
Fred Foo Avatar answered Mar 03 '23 22:03

Fred Foo