C++ Design Patterns – Are Utility Classes with Static Members an Anti-Pattern?

anti-patternscdesign-patterns

The question Where should I put functions that are not related to a class has sparked some debate over whether it makes sense in C++ to combine utility functions in a class or just have them exist as free functions in a namespace.

I come from a C# background where the latter option does not exist and thus naturally trend toward using static classes in the little C++ code I write. The highest voted answer on that question as well as several comments however say that free functions are to be preferred, even suggesting static classes were an anti-pattern. Why is that so in C++? At least on the surface, static methods on a class seem indistinguishable from free functions in a namespace. Why thus the preference for the latter?

Would things be different, if the collection of utility functions needed some shared data, e.g. a cache one could store in a private static field?

Best Answer

I guess to answer that we should compare the intentions of both classes and namespaces. According to Wikipedia:

Class

In object-oriented programming, a class is a construct that is used as a blueprint to create instances of itself – referred to as class instances, class objects, instance objects or simply objects. A class defines constituent members which enable these class instances to have state and behavior. Data field members (member variables or instance variables) enable a class object to maintain state. Other kinds of members, especially methods, enable a class object's behavior. Class instances are of the type of the associated class.

Namespace

In general, a namespace is a container that provides context for the identifiers (names, or technical terms, or words) it holds, and allows the disambiguation of homonym identifiers residing in different namespaces.

Now, what are you trying to achieve by putting the functions in a class (statically) or a namespace? I would wager that the definition of a namespace better describes your intention - all you want is a container for your functions. You don't need any of the features described in the class definition. Note that the first words of the class definition are "In object-oriented programming", yet there is nothing object-oriented about a collection of functions.

There are probably technical reasons as well but as someone coming from Java and trying to get my head around the multi-paradigm language that is C++, the most obvious answer to me is: Because we don't need OO to achieve this.