Pure and Impure Function in Java
Written by
Functions or methods can be classified into two categories:
- Pure Functions
- Impure Functions
Pure Functions :
The functions that return a value when it is invoked.
public int factorial(int a){ //Highlighted Part is first int
int i; f=1; for(i=1;i<=a;i++) f=f*i; return f; //Highlighted Part
}
Impure Functions :
The functions that do not return a value when it is invoked.
public void factorial(int a)//Highlighted Part is void{ int i; f=1; for(i=1;i<=a;i++) f=f*i;
System.out.println(f);//Highlighted Part }
Here you can observe through the highlighted part that both the functions are doing the same task but the upper one is pure as it is returning the value of f whereas the lower one is not returning anything but simply printing the value of f.
Also, there exist two distinct ways of passing values to a function:
-Pass By Reference
-Pass By Value