Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is a class with only static methods preferable to a namespace?

I was inspired by the comments under this question.

I didn't see any reason why a class with only static functions would be a better design than a namespace (with just functions). Any list of pros and cons of these two approaches are welcomed. It would be great with some practical examples!

like image 329
GuLearn Avatar asked Apr 19 '13 15:04

GuLearn


People also ask

Can a class have only static methods?

Utility Class, also known as Helper class, is a class, which contains just static methods, it is stateless and cannot be instantiated.

Why static methods are not recommended?

Static methods are bad for testability. Since static methods belong to the class and not a particular instance, mocking them becomes difficult and dangerous. Overriding a static method is not that simple for some languages.

Why are static methods better?

They are faster — Static methods are slightly faster than instance methods because in instance methods, you are also working with an implicit this parameter. Eliminating that parameter gives a slight performance boost in most programming languages.

What is the difference between a namespace and a class?

Classes are data types. They are an expanded concept of structures, they can contain data members, but they can also contain functions as members whereas a namespace is simply an abstract way of grouping items together. A namespace cannot be created as an object; think of it more as a naming convention.


1 Answers

One non-stylistic difference is that you can use a class as a template parameter, but you cannot use a namespace. This is sometimes used for policy classes, like std::char_traits.

Outside of that use case, I would stick to a namespace with regular functions.

like image 154
R. Martinho Fernandes Avatar answered Sep 23 '22 18:09

R. Martinho Fernandes