开发者

Decomposing big member function

开发者 https://www.devze.com 2023-04-08 18:50 出处:网络
Decomposing a member function In a class there is a member function that is rather long. Let\'s say we have

Decomposing a member function

In a class there is a member function that is rather long. Let's say we have

class Customer {
public:
        void process();

...
};

The method process is by nature long and consists of a couple of different steps. You'd like these steps to be functions of their own, to avoid having multiple levels of abstraction in the process method. I have thought of these different options (including the noop-alternative):

Create stand-alone functions for the steps outside of the class.

double step_a(vector<Order> orders, double foo);
void step_b(double bar);

void Customer::proccess()
{
        double foo;
        ...
        double bar = step_a(this->orders, foo);
        ...
        step_b(bar);
};

Concerns: The class is less self-contained. The stand alone functions are so specific to the process function that they would never be of interest to any other code, making it feel unnatural to keep them outside of the class.

Create private methods.

class Customer {
public:
        void process();
private:
        double step_a(double foo);
        void step_b(double bar);
};

Concerns: The private methods for the steps (at least some of them) wouldn't operate on any class members at all. They have no side effects, they only compute a value from arguments and return it, so they have no need at all to be member functions of the class.

Leave Customer::process as is

Concerns: The function becomes long, and could be hard to read, because of all the details i开发者_JS百科n the steps making it hard to see the big picture of what steps the process contains.

Question:

What would be the cleanest way to handle this?

(Perhaps none of the above, but someting I hadn't thought of.)


The question isn't really language agnostic. Not all languages have stand alone functions. In C++ or C# I would probably use private member functions (static if possible).

In C++ you could use stand-alone functions (possibly in an anonymous namespace) so they are not visible to the outside.


I'd point you at the refactoring books - especially Martin Fowler's Refactoring, and Joshua Kerievsky's Refactoring to Patterns. This problem is explored at some depth in those books.

The "stand-alone" option you describe is often called "helper methods"; there's nothing inherently wrong with this, except that they often explode into becoming the core of the method, and this leads to dependency explosion.

Private (static) methods are best if the code is directly related to the duties of the class in question.

Leaving it as is can be okay - but there's a fairly well-understood correlation between the complexity of a method and the likelihood it contains bugs. If this is a living code base, I'd refactor it.

0

精彩评论

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

关注公众号