简体   繁体   English

修改传递给方法的对象的最佳做法是什么?

[英]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? 在Java中执行此任务的最佳做法是什么?

Simple answer 简单回答

As stated in other answers, you can simply call the setter method. 如其他答案所述,您只需调用setter方法即可。

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 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. 也就是说,有时你只想在同一个逻辑范围内封装一些逻辑,你想要修改传入的对象的值。所以我要使用的规则是, 只要所有调用代码都是完整的知道这样的突变 ,你可以在你传递对象的方法中调用对象上的setter方法(并且你应该创建一个setter方法,如果你没有)。

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: 以Jigar Joshis为例:

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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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