Reputation: 3408
I have a utility class which doesn't hold any data members and just provides some services through its methods. In such a case what approach is better, create a class with all static methods or create a class with normal methods and call them by creating an object of the class? What are the pros and cons of either of the approaches?
Upvotes: 0
Views: 420
Reputation: 93264
I think the superior choice is using a namespace
and free functions. Reasons:
Using a class
with normal methods is confusing, as it needs to be instantiated but has no state.
Using a class
with only static methods is better, but requires the user to always specify the name of the class.
Using a namespace
and free functions prevents the possibility of confusing/unnecessary instantiations, and also allows the user to alias the namespace
or use using namespace
to avoid repetition when using multiple functions in the same scope. The namespace
can also span multiple files.
Upvotes: 1
Reputation: 1629
If you have no data members, there is no reason to use a class with member methods. You have to create an instance of your class to call your methods (A small, but avoidable overhead)
Calling a static method of a class generates no overhead. The same is for functions in a namespace.
Upvotes: 1