John V
John V

Reputation: 5047

Is there a case where a stateless method should not be static?

As stateless methods are mostly marked as static, they do not require the instance. But I am wondering whether there could be a case where a stateless method still can be an instance method of a class? The reason I ask is that I have read some learning materials that mention "stateless and static methods", so I am thinking about the difference.

Upvotes: 3

Views: 466

Answers (2)

GhostCat
GhostCat

Reputation: 140467

Keep in mind: depending on the used language/technology, static can be almost an anti-pattern.

In Java for example, static is implemented in a way that basically kills polymorphism. But polymorphism is one of the cornerstones of OOP. You use it to enable yourself to easily add new functionality - by extending some class and overriding a certain method. But when using static, you directly "link" yourself to that very specific class and method implementation. If you need different behaviour, you either have

  • change the caller to invoke some other method
  • change the behaviour of that static method.

And of course: again, in Java, in order to do proper unit testing, static can get in your way quickly. And most often, when people find "woha, my code under test calls that static method, and ouch, calling that static method throws up in our unit test environment" - their "answer" is to turn to mocking frameworks that allow to mock static methods (like PowerMock or JMockit). And that can lead to other issues.

Thus: static has its place, but depending on your technology stack you should be really careful about using it. Not having state is probably thus necessary, but sufficient when determining whether some method should be static or not.

Upvotes: 3

Andrey Tyukin
Andrey Tyukin

Reputation: 44918

For example if you want to make use of what is called "Strategy Pattern" in OOP-terms.

For example, if you are programming a little calculator, and you want to apply a binary operation to the two numbers on top of the stack, you want to map user input to instances of the classes Addition, Subtraction, ..., Division, which all implement an interface BinaryOperator and have a (stateless!) method int apply(int firstArg, int secondArg).

The basic arithmetic operations +, -, *, / are as stateless as anything can possibly get, but still, you are attaching them to instances of classes.

This is kind-of a canonical example, because whenever you mix OOP with purely functional programming, all objects without mutable state become something like collections of closures, which are essentially the good-old-oop-strategies on methamphetamines.

Upvotes: 2

Related Questions