Search code examples
static-methodspurely-functional

Are static methods close to pure methods?


Going by the requirements of pure method(a method which has no side effects on outside world), I have found most of the times static methods meeting this requirement. We can't access instance variables in static method, so it greatly reduces chances of side effects. Then mostly we use static methods to do some computations based on input values and just return new value...inputs are rarely mutated.

So can it be said that static methods are good enough replacement of pure methods.


Solution

  • No. Just being static does not make a function pure.

    In purely functional programming the outcome of the function should depend only on their arguments, regardless of global state. Static functions can easily access and modify global state.

    Any useful pure function must return a value. Static functions can and often are declared to be void, which makes no sense for a pure function.

    Pure functions should produce the same result for the same input each time. Any static function using a static counter could break that rule.

    In Java , for example, streams objects are functional in nature. Their functions, such as filter() , are not static, but maintain the immutability of the stream data by producing a new stream instead of modifying the original stream object.

    That being said, its easier for static functions to have no side effects, since they have 1 less thing to worry about modifying - their own instance state. Instance functions need to refrain from modifying both their own instance state, and global static state.