开发者

Converting all functions into classes

I was r开发者_JAVA技巧eading 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,


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.


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.


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

When you convert your functions to objects, you're not gaining anything. A method call is in fact the same plain function call, only with a hidden argument, this. In your case, that argument would be redundant because your object is not bearing any state.

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


Definitively no! It is no point to convert any function to class.

Class is about to manage some state of object and hide information, functions are to global and mostly stateless. A lot of lose classes make software inefficient and unmaintainable.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜