c++conventionsmutators

Is there any rule against putting more than one parameter in a mutator?


I need my mutator to call a different function in my constructor and another function anytime after that, so I was thinking of putting a bool as a second parameter to differentiate as follows:

void SetName(const char* name, bool init)
{
     init ? this(name) : that(name);
}

Is this against convention or anything? Should I use two separate mutators instead?


Solution

  • It allows you to make a mistake which can instead be prevented at compile-time. For example:

    Example example;
    example.SetName("abc", true); // called outside the constructor, `init == true` anyway
    

    To prevent such situations, just replace your

    struct Example {
        Example() { SetName("abc", true); }
        void SetName(const char* name, bool init) { init ? foo(name) : bar(name); }
    };
    

    with

    struct Example {
        Example() { foo("abc"); }
        void SetName(const char* name) { bar(name); }
    };
    

    Testing:

    Example example; // calls the for-the-constructor version
    example.SetName("abc"); // calls the not-for-the-constructor version
    example.SetName("abc", true); // obviously, doesn't compile any more