Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

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?

share|improve this question
    
Sounds a bit like the "functional decomposition" antipattern. –  user281377 Feb 11 '12 at 12:18
5  
Short answer: You just don't need a class to wrap these functions. Free functions are a much cleaner fit for your task than crunching them into some pseudo-OO construct, which is a workaround you only need in "purely-OO" languages. –  Christian Rau Feb 11 '12 at 16:02
add comment

7 Answers

up vote 25 down vote accepted

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.

share|improve this answer
add comment

If a function maintains no state and is reentrant, there doesn't seem to be much point in shoving it inside a class, (unless forced to by the language). If the function maintains some state, (eg. it can only be made thread-safe by means of a static mutex), then static methods on a class seem appropriate.

share|improve this answer
add comment

Back in the day I needed to take a FORTRAN class. I knew other imperative languages by then, so I figured I could do FORTRAN without much studying. When I turned in my first homework, professor returned it to me and asked to redo it: he said that Pascal programs written in FORTRAN syntax do not count as valid submissions.

Similar issue is in play here: using static classes to host utility functions in C++ is a foreign idiome to C++.

As you mentioned in your question, using static classes for utility functions in C# is a matter of necessity: free-standing functions are simply not an option in C#. The language needed to develop a pattern for allowing programmers define free-standing functions in some other way - namely, within static utility classes. This was a Java trick taken word-for-word: for example, java.lang.Math and System.Math of .NET are nearly isomorphic.

C++, however, offers namespaces, a different facility for achieving the same goal, and it actively uses it in the implementation of its standard library. Adding an extra layer of static classes is not only unnecessary, but also somewhat counterintuitive to readers without C# or Java background. In a sense, you are introducing a "loan translation" into the language for something that can be expressed natively.

When your functions need to share data, the situation is different. Because your functions are no longer unrelated, Singleton pattern becomes the preferred way of addressing this requirement.

share|improve this answer
2  
+1, except for recommending singletons. They are not preferred in C++! Functions may be in a class if they need to share state, but classes should not be singletons unless they really, really need to be. And they usually don't. –  Maxpm Feb 11 '12 at 18:50
    
@Maxpm Don't get me wrong, singleton is preferred only to global static variables. Other than that, there is nothing "preferred" about that. –  dasblinkenlight Feb 11 '12 at 19:47
    
There is this good article, Singletons: Solving Problems You Didn't Know You Never Had Since 1995. Summarized it says that coupling the well known instance to the class itself unnecessarily limits your flexibility and gives you nothing. Most of the time just have a class and have a shared instance somewhere, but don't make it singleton. –  Jan Hudec Feb 17 '12 at 9:00
add comment

Perhaps you need to ask why you would want an all-static class?

The only reason I can think of is that other languages (Java and C#) that are very much 'everything is a class' require them. These languages cannot create top-level functions at all, so they invented a trick to keep them, and that was the static member function. They're a bit of a workaround, but C++ doesn't need such a thing, you can create brand new top-level, independent functions directly.

If you need functions that operate on a specific data item, then it makes sense to bundle them into a class that holds the data, but then, these stop being functions and start being members of that class that operate on the class' data.

If you have a function that doesn't operate on a particular data type (I use the word here as classes are ways to define new data types) then it really is an anti-pattern to shove them into a class, for no other than semantic purposes.

share|improve this answer
6  
Indeed - I would say that the "class with all static members" in Java is actually a hack to get around a limitation of Java. –  Charles Salvia Feb 11 '12 at 15:03
    
@CharlesSalvia: I was being polite :) I have the same bad feeling about main() being part of a java class too, though I understand why they did that. –  gbjbaanb Feb 12 '12 at 13:39
    
This actually seems to provide the answer to why you'd want an all-static class. Or do I misunderstand you? For example, I need to hold a variable whose value can change that is read by one class (which I intend to store in ROM) and written to by another class (which will be in RAM). Simply placing the at a known ram location is not sufficient - wrapping it (and it's accessors) in a class allows me to fine tune access control. Pretty much what you describe in your second paragraph. –  iheanyi Jun 12 at 14:52
add comment

... 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?

An all-static class will get the job done, but it's like driving a 53-foot semi truck to the grocery store for chips and salsa when a four-door sedan will do (i.e., it's overkill). Classes come with a small amount of additional overhead and their existence might give someone the impression that instantiating one might be a good idea. The free functions offered by C++ (and C, where all functions are free) don't do that; they're just functions and nothing else.

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?

Not really. The original purpose of static in C (and later C++) was to offer persistent storage that's usable at any level of scope:

int counter() {
    static int value = 0;
    value++;
}

You can take the scope out to the level of a file, which makes it visible to all narrower scopes but not outside the file:

static int value = 0;

int up() { value++; }
int down() { value--; }

A private static class member in C++ serves the same purpose but is limited to the scope of a class. The technique used in the counter() example above also works inside C++ methods and is something I'd actually recommend doing if the variable doesn't need to be visible to the entire class.

share|improve this answer
    
+1 for at least mentioning visibility and scope –  sq33G Feb 11 '12 at 20:12
    
I suppose a group of unrelated utility functions which share no data should be better grouped in a namespace. But if you have a group of tightly coupled utility functions that need access to shared data and perhaps some access control, a static class is the best choice. A static within a function is not reentrant. Using a module global... slightly better in this context, but I still think an all static class is the best solution if you have the requirements I described. –  iheanyi Jun 12 at 14:56
add comment

I'd be very cautious in calling that an anti-pattern. Namespaces are usually prefered, but as there is no namespace templates and namespaces can't be passed as template parameters, using classes with nothing but static members is quite common.

share|improve this answer
1  
The other answers have glossed over the last line of the OP. Namespaces are pretty much named scopes, so if you need access control, classes are the only tool available. –  cmannett85 Feb 11 '12 at 11:43
1  
@cbamber85 to be fair, I had put that line in only after reading the first two answers. –  PersonalNexus Feb 11 '12 at 12:49
    
@PersonalNexus Ah fair enough, I didn't realise! –  cmannett85 Feb 11 '12 at 12:51
9  
@cbamber85: That is not entirely true. You'd get even better encapsulation by putting "private" functions in the implementation file, so the users don't get to see even the private declaration. –  UncleBens Feb 11 '12 at 13:21
2  
+1 Templates are indeed a point where namespaces still lack features. –  Christian Rau Feb 11 '12 at 16:05
show 3 more comments

At least on the surface, static methods on a class seem indistinguishable from free functions in a namespace.

In other words having a class instead of a namespace has no advantages.

Why thus the preference for the latter?

For one thing it saves you typing static all the time, though that's arguably a rather minor benefit.

The main benefit is that it's the least powerful tool for the job. Classes can be used to create objects, they can be used as the type of variables or as template arguments. Neither of those are features you want for your collection of functions. So it's preferable to use a tool that doesn't have those features, so that the class can't accidentally be misused.

Following from that using a namespace makes it also immediately clear to any users of your code that this is a collection of functions and not a blueprint to create objects from.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.