Reputation: 554
I assumed that pure functions must always have a return type (i.e., must not be void
) and must have the same output regardless of the state of the object and that Impure functions change the state of the object or print the state of the object.
But the textbook I use states that:
An accessor usually contains a return statement, but a method that prints information about an objects state may also be classified as an accessor.
I'm confused. Which one is correct?
EDIT
A bit of clarification,The thing that makes me ask is this question:
The last question is to "Give the type of function used", and the people who commented there stated that it is an impure function as it is printing.
So is this function pure or impure?
Upvotes: 22
Views: 41801
Reputation: 26332
Content taken from this link
Characteristics of Pure Function:
The return value of the pure functions solely depends on its arguments Hence, if you call the pure functions with the same set of arguments, you will always get the same return values.
They do not have any side effects like network or database calls
Characterisitcs of Impure functions
The return value of the impure functions does not solely depend on its arguments Hence, if you call the impure functions with the same set of arguments, you might get the different return values For example, Math.random(), Date.now()
They may have any side effects like network or database calls
They may modify the arguments which are passed to them
function impureFunc(value){
return Math.random() * value;
}
function pureFunc(value){
return value * value;
}
var impureOutput = [];
for(var i = 0; i < 5; i++){
impureOutput.push(impureFunc(5));
}
var pureOutput = [];
for(var i = 0; i < 5; i++){
pureOutput.push(pureFunc(5));
}
console.log("Impure result: " + impureOutput); // result is inconsistent however input is same.
console.log("Pure result: " + pureOutput); // result is consistent with same input
Upvotes: 38
Reputation: 23002
Both Statements are Correct.
When you create methods for getting value which are called ACCESSOR METHODS
Ex:
public String getName(){
return this.name;
}
and for Setting value we use methods with VOID which are called MUTATOR METHODS
Ex:
public void setName(String n){
this.name=n;
}
Upvotes: 2
Reputation: 11
Impure Functions or Mutator Methods change the state of object and modify the values that are stored in Instance Variables.
Upvotes: 1
Reputation: 201467
From Wikipedia - a function may be described as a pure function if both these statements about the function hold:
Therefore, if either statement is false when compared to your code then it is impure.
Upvotes: 8
Reputation: 36524
Mu. You seem to be assuming that an accessor is a pure function by definition. This is not necessarily the case -- an accessor (even a get
-accessor returning a value) may be impure, such as the get
method of LinkedHashMap
when in access-order mode (which moves the requested entry to last position in iteration order).
Upvotes: 4