Effective C++ Item 23 Prefer non-member non-friend functions to member functions

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.

Leave a Comment