1

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.

dbc
  • 104,963
  • 20
  • 228
  • 340
Athomas1
  • 39
  • 5
  • not everybody has to book at hand, thus it would be good, if you could include an exact quote in the question. – 463035818_is_not_an_ai Mar 23 '16 at 12:09
  • There's a "might" in the text you're referring to, and it doesn't imply that you *should* do anything in particular, except use your own good judgement to determine whether perhaps your code could benefit from being restructured. Applying this idea *might* also lead to a worse mess than you started with. – molbdnilo Mar 23 '16 at 12:25

1 Answers1

2

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.

Hong Ooi
  • 56,353
  • 13
  • 134
  • 187
Jorn Vernee
  • 31,735
  • 4
  • 76
  • 93
  • So it is about keeping a piece of data private and within the class instead of passing it between classes. Thankn you for the code example. – Athomas1 Mar 23 '16 at 14:50
  • 1
    Well, this was a simple example, so the readability improvement is not that big. But if we have, say, 20 variables that we have to pass to each function, it's a lot cleaner to pass them just once to a constructor. That's the main point they seem to be going at. The encapsulation is nice for other reasons though. – Jorn Vernee Mar 23 '16 at 16:07