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.
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.
Instance method are methods which require an object of its class to be created before it can be called. Static methods are the methods in Java that can be called without creating an object of class.
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.
A static method (or static function) is a method defined as a member of an object but is accessible directly from an API object's constructor, rather than from an object instance created via the constructor.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With