简体   繁体   中英

Streamlining Parameter Passing

I am reading through Code Complete and had a question about "Streamlining parameter passing". The author says that if you are passing a parameter among several routines, that might indicate a need to factor those routines into a class that share the parameter as class data.

Does this mean that if I have several separate class that use the same data I should create one new class that uses that data and then inherit to make new classes?

Or

Does this mean that if I have a bunch of loose routines in my program I should go ahead and put them into a class and get the benefits of encapsulation, etc.

The latter. It looks like they're talking about a case like this:

void function_1(std::string& my_data);
void function_2(std::string& my_data);

void main() {
    std::string my_data = "SomeString";
    function_1(my_data);
    function_2(my_data);
}

Which could be changed to:

class MyClass {
    std::string my_data;
public:
    MyClass(const std::string& str) : my_data(str) {}
    void function_1();
    void function_2();
}

void main() {
    MyClass obj("SomeString");
    obj.function_1();
    obj.function_2();
}

Where function_1 and function_2 use the my_data field, instead of having to be passed the string every time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM