Should a utility function be a function in an unnamed namespace, or a private member function?

810 Views Asked by At

My question is regarding the use of unnamed namespaces for organizing my code in a class.

Earlier whenever I needed some utility method, which performed some internal computation, I added a private method in the class, did the computation and used the result.

Now, instead of adding a private method to the class, I implement the same computation in the class source as a function inside an unnamed namespace, pass the required data and fetch the result. I started this practice after having read here that even private methods of a class are part of its interface and non member functions improve the encapsulation of a class.

Which of these approaches is better?

1

There are 1 best solutions below

0
On BEST ANSWER

There's much to be said for moving what could conceptually be private member functions in a client-facing header to be non-members in an anonymous namespace in the associated implementation file, largely because by not appearing in the header the client code needn't be recompiled when they're added/changed/removed, but also because of the improved class encapsulation. That said, any inline functions in the header won't be able to see/call the the anonymous namespace content, and there's no general encapsulation preventing other code later in the implementation file's translation unit from coupling to it. So, the class becomes better encapsulated at potential cost to the rest of the code in the implementation file, but that's rarely a major practical concern as those non-member functions taking a pointer or reference to an object of the class type are less prone to unintended reuse for unrelated purposes, and at least a translation unit provides a relatively small scope compared to arbitrary "client code".

That said, the trade-off's above are not what Scott Meyer's linked article is primarily about - that focuses on the choice of non-member non-friend functions declared in the header vs. public member functions. Several concepts apply though, as you've obviously noticed.