tags:

views:

141

answers:

2

Lets say I need to write several functions processing some data. These functions are performing a single task - some mathematical calculations. I suppose there is no need to combine them with some data members.

Shall I use:

  1. a class without data members and declare these functions as static methods so I can use them without creating class object,
  2. or an anonymous namespace,
  3. or maybe I need something more complicated in terms of architecture and design?

Actually, the language I am writing in is C++, but I think this question doesn't depend on what the language of development is.

+2  A: 

In C++, I'd use a utility namespace, not a class with only static methods.

MadKeithV
so it can be anonymous namespace holding all these functions?
chester89
See ckarmann's answer below for why anonymous namespaces might not be the best idea.
MadKeithV
In C++, the general rule is to prefer free functions when possible. (As MadKeithV suggests)Only make class member functions when that's actually what you *need*
jalf
+2  A: 

I don't see why you would put them in an anonymous namespace. It is done to make sure these functions are only used in one compilation unit, which has nothing to do with your question.

Now, to choose between static functions in a class or free functions in a utility namespace, it's up to your needs. There is a few differences between these solutions:

  • In classes, you can set some functions as private, protected or public. For example you may have private functions to do common things which are needed by your public functions.
  • Namespaces can be extended and their definition spread in several files.
  • Classes can be subclassed (and so their functionality can be extended too). You can have a model with protected static functions and client classes subclassing this class for better encapsulation.
ckarmann
Personally, I don't like "inheritance abuse" - if the subclass is not a Liskov substitute. But you CAN of course use protected or private inheritance. Thank goodness for the dark corners of C++ ;-)
MadKeithV
I agree that it is a bit an abuse of the inheritance concept. :) I wouldn't advise to do that too, but I wanted to say it is a possibility.
ckarmann