Why Are There So Many Instantiable Classes Without State?

cclassjavaobjectobject-oriented

I'm seeing a lot of instantiable classes in the C++ and Java world that don't have any state.

I really can't figure out why people do that, they could just use a namespace with free functions in C++, or a class with a private constructor and only static methods in Java.

The only benefit I can think of is that you don't have to change most of your code if you later decide that you want a different implementation in certain situations. But isn't that a case of premature design? It could be turned into a class later, when/if it becomes appropriate.

Am I getting this wrong? Is it not OOP if I don't put everything into objects (i.e. instantiated classes)? Then why are there so many utility namespaces and classes in the standard libraries of C++ and Java?

Update:
I've certainly seen a lot examples of this in my previous jobs, but I'm struggling to find open source examples, so maybe it's not that common after all. Still, I'm wondering why people do it, and how common it is.

Best Answer

I'm seeing a lot of instantiable classes in the C++ and Java world that don't have any state.

Some possibile reasons to create classes without ivars of their own:

  • State is or could be contained in a superclass.

  • Class implements some interface and needs to be instantiable so that instances can be passed to other objects.

  • Class is intended to be subclassed.

  • Handy way to group related functions. (Yes, there may be better or different ways to do the same.)

Am I getting this wrong? Is it not OOP if I don't put everything into objects (i.e. instantiated classes)?

OOP is a paradigm, not a law of nature. There are some languages where everything is an object, so you really don't have a choice. Other languages (e.g. C) don't provide any support for OOP at all, but you can still program in an object oriented style. I'd say you can have OOP if you don't do everything in classes... you might say that you just have less OOP in that case.

Related Topic