为方法参数分配一个新值是否有问题? [英] Is it problematic to assign a new value to a method parameter?

查看:158
本文介绍了为方法参数分配一个新值是否有问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Eclipse有一个选项,可以在方法的参数(方法里面)中对赋值进行警告,如:

Eclipse has an option to warn on assignment to a method's parameter (inside the method), as in:

public void doFoo(int a){
   if (a<0){
      a=0; // this will generate a warning
   }
   // do stuff
}

通常我尝试激活(注意)几乎所有可用的编译器警告,但在这种情况下,我不确定是否值得。

Normally I try to activate (and heed) almost all available compiler warnings, but in this case I'm not really sure whether it's worth it.

我查看方法中更改参数的合法情况(例如:允许参数为未设置(例如,null)并自动替换默认值),但是会导致问题的情况很少,但可能会有点混乱在方法中间重新分配一个参数。

I see legitimate cases for changing a parameter in a method (e.g.: Allowing a parameter to be "unset" (e.g. null) and automatically substituting a default value), but few situations where it would cause problems, except that it might be a bit confusing to reassign a parameter in the middle of the method.

你是否使用这样的警告?为什么/为什么不?

Do you use such warnings? Why / why not?

注意:

避免此警告当然等于使方法参数 final (只有这是一个编译器错误:-))。所以这个问题为什么我应该使用关键字最终对于Java中的方法参数可能是相关的。

Avoiding this warning is of course equivalent to making the method parameter final (only then it's a compiler error :-)). So this question Why should I use the keyword "final" on a method parameter in Java? might be related.

推荐答案

对于我来说,只要你早点很明显,没关系正如你所说,把它埋在深入四条条件的中途进入一个30行的功能是不太理想的。

For me, as long as you do it early and clearly, it's fine. As you say, doing it buried deep in four conditionals half-way into a 30-line function is less than ideal.

你也显然要小心,当这样做使用对象引用,因为调用对象的方法可能会更改其状态并将信息传递给调用者,但当然,如果您已经将其隐藏在自己的占位符中,那么该信息就不会传达。

You also obviously have to be careful when doing this with object references, since calling methods on the object you were given may change its state and communicate information back to the caller, but of course if you've subbed in your own placeholder, that information is not communicated.

另一方面,声明一个新的变量并赋予参数(或默认的if参数需要默认)可能会更加清晰,几乎肯定不会那么有效 - 任何体面的编译器(无论是主编译器还是JIT)都可以在可行时优化它。

The flip side is that declaring a new variable and assigning the argument (or a default if argument needs defaulting) to it may well be clearer, and will almost certainly not be less efficient -- any decent compiler (whether the primary compiler or a JIT) will optimize it out when feasible.

这篇关于为方法参数分配一个新值是否有问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆