副作用对我的代码

时间:2017-05-10 15:35:00

标签: java effects

我目前对编程中的副作用了解不多,所以我很好奇我的代码下面有任何副作用。

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);    
   }  

}  

1 个答案:

答案 0 :(得分:1)

factorial没有任何副作用,因为它计算一个值并返回它,而不修改函数外部的任何内容。另一方面,main具有打印阶乘的副作用。这是一个很好的设计,因为factorial函数不应该有任何副作用;它应该只计算阶乘。

请参阅https://softwareengineering.stackexchange.com/questions/40297/what-is-a-side-effect