Functional Programming With Java 简明教程
Functional Programming - Pure Function
如果函数满足以下两个条件,则该函数被视为纯函数:
-
对于给定的输入,它始终返回相同的结果,并且其结果完全取决于传递的输入。
-
它没有副作用,这意味着它不修改调用方实体的任何状态。
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;
}
}