在同一java类中作为方法参数的全局变量:这是一种糟糕的编程实践吗?
下面的代码工作得很好。但是作为一个新手,我不确定将全局变量作为同一个java类中的参数传递到私有方法中是否是一种不好的做法。这可以接受吗?如果这是一个糟糕的编程,是否有更好或更可接受的方法在同一java类中作为方法参数的全局变量:这是一种糟糕的编程实践吗?,java,global-variables,parameter-passing,Java,Global Variables,Parameter Passing,下面的代码工作得很好。但是作为一个新手,我不确定将全局变量作为同一个java类中的参数传递到私有方法中是否是一种不好的做法。这可以接受吗?如果这是一个糟糕的编程,是否有更好或更可接受的方法 @Value("${canDeleteAllBefore:true}") private boolean canDeleteAllBefore; @Value("${canDeleteAllAfter:false}") private boolean canDelete
@Value("${canDeleteAllBefore:true}")
private boolean canDeleteAllBefore;
@Value("${canDeleteAllAfter:false}")
private boolean canDeleteAllAfter;
@Value("${canExecute:true}")
private boolean canExecute;
public ConsoleApp(@Value("${canDeleteAllBefore:true}") String canDeleteAllBefore,
@Value("${canDeleteAllAfter:true}") String canDeleteAllAfter,
@Value("${canExecute:true}") String canExecute) {
setboolean(canDeleteAllBefore, "canDeleteAllBefore", this.canDeleteAllBefore);
setboolean(canDeleteAllAfter, "canDeleteAllAfter",this.canDeleteAllAfter);
setboolean(canExecute, "canExecute",this.canExecute);
}
private void setboolean(String booleanValue, String propertyName, boolean boolValue) {
if (booleanValue.equalsIgnoreCase("true") || booleanValue.equalsIgnoreCase("false")) {
boolValue = Boolean.parseBoolean(booleanValue);
}
else {
System.out.println(booleanValue + " is not a boolean value. " +
"Please use either true or false as a value for the property " + propertyName);
System.exit(1);
}
}
如果预期
setboolean
方法将更改canExecute
字段的值,那么很遗憾,这是不正确的
所以当你打这个电话的时候
setboolean(canExecute, "canExecute",this.canExecute)
它将实际获取this.canExecute的当前值并将其传入。方法setboolean
不知道该值来自何处
因此,当setboolean
更新参数值时,它不会在该函数的范围之外产生任何影响
因此,在你的情况下,更有意义的是:
private boolean setboolean(String booleanValue, String propertyName, boolean boolValue) {
if (booleanValue.equalsIgnoreCase("true") || booleanValue.equalsIgnoreCase("false")) {
return Boolean.parseBoolean(booleanValue);
}
throw new Exception("invalid value");
}
然后使用函数this.canExecute=setboolean(…)代码>仅使用函数的返回值
还有另一种方法。您可能想看看
BooleanHolder
,它的作用类似于基本布尔值的包装器。这样做的好处是,您可以将其传递给其他人并更改持有者的内容。这与您尝试执行的操作非常接近。您的代码执行了奇怪的操作。我认为最好给出一个更现实的例子:不使用变量propertyName,变量条件缺失,设置布尔值不起任何作用,因为它没有进一步的用途。我希望您不要期望这个booleanValue=
修改类级别字段的值。因为它不会。它只是在本地作用于参数值。@bvdb,我试图缩短并给出我的代码的简明版本。我将添加部件。我希望我的回答能澄清一些问题。我理解代码中的问题。非常感谢。你的解决方案不是我想要的。但也许我该怎么做@armel我又添加了一个选项,这可能会引起您的兴趣。@bvdp,这实际上就是我的想法。非常感谢!:)