C++ function called in multiple places, how to refactor to accept a new argument?

116 Views Asked by At

I have this function f(MyType a, b) and I want to it to become f(MyType a, b, c). The problem is that f is called by multiple other functions (g(), h(), i()) which in turn are called by multiple other functions. I would need to pass the new argument int c down to all functions so they can pass it to f().

I would like this:

int f(TypeA a, TypeB b);

int g(TypeA a, TypeB b) { 
    f(a, b);
}

int r(TypeA a, TypeB b) {
    g(a, b);
}

To become this:

int f(TypeA a, TypeB b, TypeC c);

int g(TypeA a, TypeB b, TypeC c) { 
    f(a, b, c);
}

int r(TypeA a, TypeB b, TypeC c) {
    g(a, b, c);
}

How could I automate this? Is there any other elegant solution I'm not seeing?

Global mutable state is undesirable. I've considered creating a singleton class with setters and getters to avoid any unwanted side effects but MyType is already used in a lot of places and I would need to refactor those instead.

1

There are 1 best solutions below

1
Jesús Jangwon Kim On

If those functions need exactly the same arguments, why not grouping them into a struct?

struct Grouped
{
    TypeA a;
    TypeB b;
    TypeC c;
};

Once you do this, you just need to modify this 'Grouped' struct and no changes need to be done for the function signatures that are taking 'Grouped' struct as their arguments.