I need to combine several methods without adding some data members. Any ideas?
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:
- a class without data members and declare these functions as static methods so I can use them without creating class object,
- or an anonymous namespace,
- 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.
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.
In C++, I'd use a utility namespace, not a class with only static methods.