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

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

    Assigning a method parameter is not something most people expect to happen in most methods. Since we read the code with the assumption that parameter values are fixed, an assignment is usually considered poor practice, if only by convention and the principle of least astonishment.

    There are always alternatives to assigning method parameters: usually a local temporary copy is just fine. But generally, if you find you need to control the logic of your function through parameter reassignment, it could benefit from refactoring into smaller methods.

提交回复
热议问题