I need to combine multiple methods without adding some data items. Any ideas?

Let's say I need to write some functions to process some data. These functions do one thing — some math. I suppose there is no need to combine them with some data items.

Should I use:

  • class with no data members and declare these functions as static methods, so I can use them without creating a class object,
  • or anonymous namespace,
  • or maybe I need something more complex in terms of architecture and design?

Actually, the language I am writing in is C ++, but I think this question is development language independent.

+1


source to share


2 answers


I don't understand why you are putting them in an anonymous namespace. This is to ensure that these functions are only used in one compilation unit, which has nothing to do with your question.

Now, to choose between static functions in the class or free functions in the utility namespace, it depends on your needs. There are several differences between these solutions:



  • In classes, you can set some functions as private, protected, or public. For example, you can have private functions to do common things that your public functions need.
  • Namespaces can be extended and their definition is spread across multiple files.
  • Classes can be subclassed (and therefore their functionality can be extended as well). You can have a model with protected static functions and client classes, subclasses of this class for better encapsulation.
+2


source


In C ++, I would use a utility namespace rather than a class with only static methods.



+2


source







All Articles