2
\$\begingroup\$

Uncle Bob in his Clean Code says:

So all the same rules apply. Functions that take variable arguments can be monads, dyads, or even triads. But it would be a mistake to give them more arguments than that.

void monad(Integer... args); void
dyad(String name, Integer... args);
void triad(String name, int count, Integer... args);

So Uncle Bob suggests that no more than 3 arguments should a function get, right?

But what about CTOR arguments in class inheritance hierarchy? What if each class in hierarchy adds a new field and you should initialize them in CTOR. See an example below:

class Person
{
private:
    std::string m_name;
    int m_age;

public:
    Person(const std::string& name, const int age);
    std::string getName() const { return m_name; }
    int getAge() const { return m_age; }
    ~Person();
};


#include "Person.h"
class Student : public Person
{
private:
    std::string m_university;
    int m_grade;

public:
    Student(const std::string& name, const int age, const std::string& university, const int grade);
    std::string getUniversity() const { return m_university; }
    int getGrade() const { return m_grade; }
    ~Student();
};

See how student gets 4 arguments, while Person gets only 2 and Student adds two more. So how we should handle this?

\$\endgroup\$
1
  • \$\begingroup\$ This is not about inheritance. Even if Student did not derive from Person, it would still have 4 arguments. \$\endgroup\$ Oct 1, 2016 at 8:17

1 Answer 1

1
\$\begingroup\$

So Uncle Bob suggests that no more than 3 arguments should a function get, right?

No. The guy you're referring to suggests that more than two arguments to a function which takes "variable arguments" is bad.

The key to understanding lies in distinguishing between a single argument (int count) and argument pack (Integer ... args). The function which takes the latter is what is called variable number arguments function, compared to fixed number argument function. The three dots here are actually part of the C++ syntax going back to C called ellipsis. Google variadic to impress people)

So if Student ctor takes 4 args (or 10 args) its ok. But if amongst the args Student Ctor takes is an argument pack, then don't overcomplicate things, by passing too many single arguments. Separate the handling of the argument packs (yes, there can be more than one pack) from the rest of them.

\$\endgroup\$

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.