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?