简体   繁体   中英

What is the best practice to modify an object passed to a method

After passing an object into a method, I would like to change one of its fields. What's the best practice to do this task in Java?

Simple answer

As stated in other answers, you can simply call the setter method.

More philosophical answer

Generally, it can be dangerous to mutate objects in a scope other than that in which they were created:

http://en.wikipedia.org/wiki/Functional_programming

That said, there are often times where you simply want to encapsulate bits of logic in the same logical scope where you would want to modify values of an object passed in. So the rule I would use is that as long as all calling code is fully aware of such mutations , you can call the setter method on the object (and you should create a setter method if you don't have one) in the method to which you're passing the object.

In general, if you call a function that mutates parameters from multiple places in your codebase, you will find that it becomes increasingly error prone, which is why functional programming pays off.

So, the moral of the story is: if your caller(s) are fully aware of such mutations, you could change the value in your method, but in general you should try to avoid it and instead change it in the scope in which it was created (or create a copy).

Be aware of the fact that even if the object is passed as final it still can be changed. You just can't reassign the variable, which normally is desired for an (input/)output parameter.

Taking Jigar Joshis example:

public void increasePersonAgeByOneMonth(final Person p ){
  p = new Person(); //this won't work, which is ok since otherwise the parameter itself would not be changed by the next method
  p.setAge(((p.getAge()*12.0) + 1)/12.0); //ok
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM