Java 如何重写程序以消除副作用?
我试图在java教科书中研究这个问题。 问题是重写这个程序来消除副作用, 对象或程序变量的状态变化是通过调用函数(或方法,类似于此)产生的 包装副作用Java 如何重写程序以消除副作用?,java,lambda,functional-programming,Java,Lambda,Functional Programming,我试图在java教科书中研究这个问题。 问题是重写这个程序来消除副作用, 对象或程序变量的状态变化是通过调用函数(或方法,类似于此)产生的 包装副作用 public class SideEffect { **public static int x;** public static int f(int n){ x = x * 2; return x + n; } /** * @param args the command
public class SideEffect {
**public static int x;**
public static int f(int n){
x = x * 2;
return x + n;
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
x = 5;
//int result = f(x) + f(x);
int result = 2 * f(x);
//System.out.println(result);
}
}
public class SideEffect {
public static int f(int x, int n){
x = x * 2;
return x + n;
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
int x = 5;
int result = f(x , 5) + f(x, 5);
System.out.println(result);
}
}
注释掉的行是当我实现整型变量并将其打印输出时发生的。
如果我实现这些行并注释掉其他行,
结果是45。
如果实施另一个,,
结果是30。
有没有一种方法可以理顺这个程序,这样就不会有副作用?
我想我删除了全局变量行,因为书中说它会导致这种不好的结果,
混乱的代码。
但是我还能尝试什么呢?我知道这是一项任务,但像这样的事情总是有点让人发疯。“问题”是他们使用全局变量的方式永远不应该使用它。“医生,我这样做很痛,不要那样做。” 通常,静态(类级别)变量很少是您真正想要的。main()还用于实例化对象并使其在世界上消失,而不是像C程序那样执行繁重的操作 创建类并传递值。不要使用全局变量,除非你真的想要有一个且只有一个实例
这是我能提供的最好的结果,因为你的问题不清楚什么是“正确的”结果。这可能有效,但我不确定。我已经注释了全局变量,然后在f方法和main方法中声明了int x。结果是,无论我是否使用“int-result”调用,它仍然将是10作为输出。但我可能是错的,因为:
public class SideEffect {
**//public static int x;**
public static int f(int n){
int x = 0;
x = x * 2;
return x + n;
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
int x = 5;
//int result = f(x) + f(x);
int result = 2 * f(x);
System.out.println(result);
//System.out.println(result2);
}
}
好吧,更好得多: 包装副作用
public class SideEffect {
**public static int x;**
public static int f(int n){
x = x * 2;
return x + n;
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
x = 5;
//int result = f(x) + f(x);
int result = 2 * f(x);
//System.out.println(result);
}
}
public class SideEffect {
public static int f(int x, int n){
x = x * 2;
return x + n;
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
int x = 5;
int result = f(x , 5) + f(x, 5);
System.out.println(result);
}
}
我在公共静态int中以int的形式输入x,因此我不必初始化变量。您想要的输出是什么?问题并没有说明具体的输出。它只建议让函数接受x的值作为参数,而不是修改全局变量。我想“消除副作用”是指方法执行产生的外部可见的副作用。还有其他类型的副作用,这在Java中是很难避免的。去掉全局变量是正确的。如果您不知道程序的输出应该是什么,那么很难修复程序,因此很难说
f
函数的实现应该是什么。程序的全部目的是产生副作用。如果你的程序没有副作用,比如print语句,你可以用一个完全空的程序来替换它。你可以重写为:publicstaticintf(intn){returnn;}
可能不是你想要的。