我目前对编程中的副作用了解不多,所以我很好奇我的代码下面有任何副作用。
class Factorial {
static int factorial(int n) {
if (n == 0)
return 1;
else
return(n * factorial(n-1));
}
public static void main(String args[]) {
int number = 4; // It is the number to calculate factorial
int fact = factorial(number);
System.out.println("Factorial of " + number + " is: " + fact);
}
}
答案 0 :(得分:1)
factorial
没有任何副作用,因为它计算一个值并返回它,而不修改函数外部的任何内容。另一方面,main
具有打印阶乘的副作用。这是一个很好的设计,因为factorial
函数不应该有任何副作用;它应该只计算阶乘。
请参阅https://softwareengineering.stackexchange.com/questions/40297/what-is-a-side-effect