Is it problematic to assign a new value to a method parameter?

后端 未结 8 554
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-10 01:17

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         


        
8条回答
  •  再見小時候
    2020-12-10 01:55

    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.

    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.

提交回复
热议问题