Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>First, not everyone agrees with this advice. I don't think I've seen anyone but Meyers (<strong>edit:</strong> and <a href="http://www.gotw.ca/gotw/084.htm" rel="noreferrer">Herb Sutter</a>) give this advice, and I've only seen it given within the context of C++. For example, creating "non-member non-friend functions" in Java or C# isn't really possible, since Java and C# have no free functions, and Ruby developers (for example) prefer <a href="http://martinfowler.com/bliki/HumaneInterface.html" rel="noreferrer">"humane interfaces"</a> that intentionally create member functions that do the same thing non-members could, just to make life easier on those functions' callers. </p> <p>And even if you do accept Meyers' advice, that you should prefer non-member non-friend functions to member functions (and I think it's good advice, it certainly helped me apply encapsulation better to think of encapsulating a class's implementation even from its member functions), that's only one axis of design to consider.</p> <p>The key concept of object-oriented design is that objects <i>do something</i>. An object isn't simply a bag of setters and getters that other code does stuff to. Instead, it should have behavior attached - that is, it should have methods that do things - and it should encapsulate the details of how it does those things. If you follow this approach to OO, then carrying Meyers' advice to the extreme as you did hurts encapsulation rather than helping it: you end up exposing all of the class's internal implementation variables via getters and setters instead of hiding them so that only the class's methods (the code responsible for <i>doing stuff</i> on behalf of the class, which is the only reason you have a class to begin with) can get to it.</p> <p>So to answer your question of how far to take Meyers' advice: Don't <i>needlessly</i> turn functions into member functions if they could reasonably be implemented as non-friend non-member functions using a class's public interface, but don't damage a class's public interface and violate its encapsulation by exposing implementation <i>just to</i> avoid making something a member. And make sure you balance encapsulation against other concerns and other approaches (including, if your team decides to go that route, the pros and cons of a full-blown humane interface).</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload