Amith KK Amith KK - 1 month ago 41
Java Question

Difference between pure and impure function?

I assumed that pure functions must always have a return type(ie, 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 comented there stated that it is an impure function as it is printing.

So is this function pure or impure?

Answer

From Wikipedia - a function may be described as a pure function if both these statements about the function hold:

  1. The function always evaluates the same result value given the same argument value(s). The function result value cannot depend on any hidden information or state that may change as program execution proceeds or between different executions of the program, nor can it depend on any external input from I/O devices.
  2. Evaluation of the result does not cause any semantically observable side effect or output, such as mutation of mutable objects or output to I/O devices.

Therefore, if either statement is false when compared to your code then it is impure.