1

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.

10
  • Have you considered making parameter c optional by providing a default value? Commented Aug 18, 2022 at 17:34
  • @jkb Unfortunately MyType c has to be initialized from command line arguments and 'f()` always needs it. There is no meaningful default value I could provide. Commented Aug 18, 2022 at 17:37
  • @user17732522 The arguments have different types, I will change the example to reflect that. Commented Aug 18, 2022 at 17:39
  • As far as recommendations for any tools, for this: this would not be an appropriate question for Stackoverflow -- software recommendations are not allowed here. Commented Aug 18, 2022 at 17:43
  • There's very little in C++ that's "automated". Every instances of these parameters getting passed must be updated accordingly. It must be done. The only good news is that as long as every function's parameters need to change, change them to simply pass a single structure, by reference, with a, b, and c. Then, if you need to add d later it needs to be done in only one place. When the initial design proves to be unworkable, there is no alternative to paying the price and redesigning everything from scratch. Commented Aug 18, 2022 at 17:47

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I would still need to change all functions, which is what I was trying to avoid. I will probably just go with a singleton class and make the fields immutable after set() is called once.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.