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

后端 未结 8 550
佛祖请我去吃肉
佛祖请我去吃肉 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 02:15

    Reassigning to the method parameter variable is usually a mistake if the parameter is a reference type.

    Consider the following code:

    MyObject myObject = new myObject();
    myObject.Foo = "foo";
    doFoo(myObject);
    
    // what's the value of myObject.Foo here?
    
    public void doFoo(MyObject myFoo){   
       myFoo = new MyObject("Bar");
    }
    

    Many people will expect that at after the call to doFoo, myObject.Foo will equal "Bar". Of course, it won't - because Java is not pass by reference, but pass by reference value - that is to say, a copy of the reference is passed to the method. Reassigning to that copy only has an effect in the local scope, and not at the callsite. This is one of the most commonly misunderstood concepts.

    0 讨论(0)
  • 2020-12-10 02:15

    I usually don't need to assign new values to method parameters.

    As to best-practices - the warning also avoids confusion when facing code like:

           public void foo() {
               int a = 1;
               bar(a);
               System.out.println(a);
           }
    
           public void bar(int a) {
               a++;
           }
    
    0 讨论(0)
提交回复
热议问题