2

There is a popular guideline (Scott Meyers, Klaus Iglberger, ect) that I recently put more thought into, which is basically prefer non-member (free) functions to member functions. I'm noticing that I can indeed actually pull most of my member functions outside, but I'm having a hard time figuring out when that's actually what I should do.

Here is a simple example, a function that prints a vector of strings (a private data member) to console in some formatted way:

void list::print() const {
    std::cout << "Printing list -> " << list_.size() << " entries.\n";
    std::cout << "--- START OF LIST ---\n";
    for (const auto &s : list_) {
        std::cout << s.size() << " : " << s << '\n';
    }
    std::cout << "--- END OF LIST ---\n";
}

I find it difficult to decide in simple cases like this, it seems to me that in the short term the member function is a bit more elegant whilst a free function can adapt to multiple objects as a program gets larger. Does anyone have some kind of rule of thumb to help decide? Am I just overthinking this? Thanks.

Jive Dadson
  • 16,680
  • 9
  • 52
  • 65
ricco19
  • 713
  • 5
  • 16
  • 1
    You already have a rule-of-thumb: "prefer non-member (free) functions to member functions." – Justin May 18 '18 at 18:36
  • Yes, prefer free-standing functions to the class members, provided they can operate on public member. Do **not** create a free-standing function only to declare it a friend. If you have more specific question ask away, but as it stands this question needs to be closed as opinion-based. – SergeyA May 18 '18 at 18:36
  • 3
    Make your class iterable, then you can use it in pretty much any generic function. – NathanOliver May 18 '18 at 18:37
  • 6
    Distinguishing between "good design" and "over-engineering" is one of the primary challenges of software design. Most developers won't agree on where the line is, you'll always find someone that disagrees with your assessment if you look hard enough and it's usually a question of perspective. – François Andrieux May 18 '18 at 18:40
  • 2
    So, basically, this is opinion based? – ricco19 May 18 '18 at 18:49

0 Answers0