Functional Programming With Java 简明教程
Functional Programming - Pure Function
如果函数满足以下两个条件,则该函数被视为纯函数:
A function is considered as Pure Function if it fulfils the following two conditions −
-
It always returns the same result for the given inputs and its results purely depends upon the inputs passed.
-
It has no side effects means it is not modifying any state of the caller entity.
Example- Pure Function
public class FunctionTester {
public static void main(String[] args) {
int result = sum(2,3);
System.out.println(result);
result = sum(2,3);
System.out.println(result);
}
static int sum(int a, int b){
return a + b;
}
}
Example- Impure Function
public class FunctionTester {
private static double valueUsed = 0.0;
public static void main(String[] args) {
double result = randomSum(2.0,3.0);
System.out.println(result);
result = randomSum(2.0,3.0);
System.out.println(result);
}
static double randomSum(double a, double b){
valueUsed = Math.random();
return valueUsed + a + b;
}
}