修改传递给方法的对象的最佳做法是什么? [英] What is the best practice to modify an object passed to a method

查看:68
本文介绍了修改传递给方法的对象的最佳做法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将对象传递给方法后,我想更改其中一个字段。在Java中执行此任务的最佳做法是什么?

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?

推荐答案

简单回答



如其他答案中所述,您可以简单地调用setter方法。

Simple answer

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

通常,在创建它们之外的范围内变异对象可能很危险:

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

那说,经常有你只想在同一逻辑范围内封装逻辑位,你想要修改传入的对象的值。所以我会使用的规则就是,只要所有调用代码都完全知道这些突变,你可以在你传递对象的方法中调用对象上的setter方法(你应该创建一个setter方法,如果你没有)。

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).

这篇关于修改传递给方法的对象的最佳做法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆