Does a pure method have to be static?

  • A+

I'm working through a textbook at the moment which defines a pure method as:

"a static method that depends only on its parameters and no other data"

Would it not be possible to have an instance method be a pure method without it being static (as long as it doesn't modify parameters and doesn't have 'side-effects' like printing)?

I know for a pure method to be the pure, the return value only depends on the parameters and not on any other state, so perhaps the way instance methods are called means that the variables taken from the object calling the method don't count as parameters but as another "state"?

Other than that I can't think of any reason why a non-static method couldn't be a pure method.

Here's an example:

public class Rational {      private int numer;     private int denom;      public Rational() {         this.numer = 0;         this.denom = 1;     }      public Rational(int numer, int denom) {         this.numer = numer;         this.denom = denom;     } } 

The above defines a Rational class

You could then write a method in the Rational class which returns a Rational object as a double by either 'Method one' or 'Method two' below.

Method one:

public double toDouble() {     double x = this.numer;     double y = this.denom;     double fprat = x / y;     return fprat; }    

Method two:

public static double toDouble(Rational rational) {     double x = rational.numer;     double y = rational.denom;     double fprat = x / y;     return fprat; }  

They essentially do exactly the same thing but one is a static method and the other is an instance method so their calls would be in a different format. Method two is certainly a pure method but would Method one, which is non-static, also be defined as a pure method under these circumstances?

The "static" part of that definition is superfluous. A method being static doesn't guarantee that it does not rely on any other state. I suspect the definition just wanted to make sure the method does not use instance variables.

On the other hand, technically you may also think of an instance method as a static method with a zero-th parameter, the object itself. If that object is immmutable (or the method does not change anything in the object), you could argue that the method is still pure. Basically you regard the "object" as an additional parameter.

Method references in Java for example can behave this way, making the first argument the object itself on which the method is called.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: