Search code examples
c++functionnamed-parameters

how to deal with situation when function has lot of params and client code needs only change only few of them?


How to not get lost in that case ? Example, this is a function that returns bool but takes on 10 params:

bool myFunc(bool par1 = true, bool par2 = false, bool par3 = true,
  bool par4 = true /* and so on */ ) {}

And let's say that the function params are set default for 90% cases. But occasionally client code wants to change only a few of them. The only option I see here is painstakingly copy all the default params until we get to the one that needs to change. Any chance of calling this function in this way:

bool myVal = myFunc(par10 = true, par20 = false);

So any who reads the code know what is going (the names of the params are very long but meaningful) with the code and moreover when I change the function definition I won't need to look whenever it is called to update the default params ?


Solution

  • There is an idiom that is moderately famous: the Named Parameters Idiom.

    The idea is simple:

    class Parameters {
    public:
        Parameters(): _1(true), _2(false), _3(true), _4(true) {}
    
        bool get1() const { return _1; }
        bool get2() const { return _2; }
        bool get3() const { return _3; }
        bool get4() const { return _4; }
    
        Parameters& set1(bool t) { _1 = t; return *this; }
        Parameters& set2(bool t) { _2 = t; return *this; }
        Parameters& set3(bool t) { _3 = t; return *this; }
        Parameters& set4(bool t) { _4 = t; return *this; }
    
    private:
        bool _1;
        bool _2;
        bool _3;
        bool _4;
    };
    
    bool myFunc(Parameters p);
    

    Then the client can do:

    result = myFunc(Parameters());
    

    Or:

    result = myFunc(Parameters().set4(false));