Effective C++ Item 23 Prefer non-member non-friend functions to member functions
The criteria I use is if a function could be implemented significantly more efficiently by being a member function, then it should be a member function. ::std::sort
does not meet that definition. In fact, there is no efficiency difference whatsoever in implementing it externally vs. internally.
A vast efficiency improvement by implementing something as a member (or friend) function means that it greatly benefits from knowing the internal state of the class.
Part of the art of interface design is the art of finding the most minimal set of member functions such that all operations you might want to perform on the object can be implemented reasonably efficiently in terms of them. And this set should not support operations that shouldn't be performed on the class. So you can't just implement a bunch of getter and setter functions and call it good.
Access to the book is by no mean necessary.
The issues we are dealing here are Dependency and Reuse.
In a well-designed software, you try to isolate items from one another so as to reduce Dependencies, because Dependencies are a hurdle to overcome when change is necessary.
In a well-designed software, you apply the DRY principle (Don't Repeat Yourself) because when a change is necessary, it's painful and error-prone to have to repeat it in a dozen different places.
The "classic" OO mindset is increasingly bad at handling dependencies. By having lots and lots of methods depending directly on the internals of the class, the slightest change implies a whole rewrite. It need not be so.
In C++, the STL (not the whole standard library), has been designed with the explicit goals of:
- cutting dependencies
- allowing reuse
Therefore, the Containers expose well-defined interfaces that hide their internal representations but still offer sufficient access to the information they encapsulate so that Algorithms may be executed on them. All modifications are made through the container interface so that the invariants are guaranteed.
For example, if you think about the requirements of the sort
algorithm. For the implementation used (in general) by the STL, it requires (from the container):
- efficient access to an item at a given index: Random Access
- the ability to swap two items: not Associative
Thus, any container that provides Random Access and is not Associative is (in theory) suitable to be sorted efficiently by (say) a Quick Sort algorithm.
What are the Containers in C++ that satisfy this ?
- the basic C-array
deque
vector
And any container that you may write if you pay attention to these details.
It would be wasteful, wouldn't it, to rewrite (copy/paste/tweak) sort
for each of those ?
Note, for example, that there is a std::list::sort
method. Why ? Because std::list
does not offer random access (informally myList[4]
does not work), thus the sort
from algorithm is not suitable.