How would you fix the following bad code that passes too many parameters around?
void helper1(int p1, int p3, int p5, int p7, int p9, int p10) {
// ...
}
void helper2(int p1, int p2, int p3, int p5, int p6, int p7, int p9, int p10) {
// ...
}
void foo(int p1, int p2, int p3, int p4, int p5, int p6, int p7, int p8,
int p9, int p10) {
helper1(p1, p3, p5, p7, p9, p10);
helper2(p1, p2, p3, p5, p6, p7, p9, p10);
}
I see two different approaches:
Approach 1: Put all functions in a class
class Foo {
private:
int p1, p2, p3, p4, p5, p6, p7, p8, p9, p10;
void helper1() {}
void helper2() {}
public:
void foo() {
helper1();
helper2();
}
// add constructor
};
Approach 2: Just pass parameters as a class
struct FooOptions {
int p1, p2, p3, p4, p5, p6, p7, p8, p9, p10;
};
void helper1(const FooOptions& opt) {
// ...
}
void helper2(const FooOptions& opt) {
// ...
}
void foo(const FooOptions& opt) {
helper1(opt);
helper2(opt);
}
What are the advantages and disadvantages of the approaches?
An advantage of Approach 1 is that -- if you make the helper
functions virtual -- you can subclass and overload them, adding flexibility. But then, in my case (outside of the toy mini example that I gave) such helpers are often templated, so they cannot be virtual anyway.
An advantage of Approach 2 is that the helper functions can easily be called from other functions, too.
(This question is related, but does not discuss these two alternatives.)