在方法(在Java中)中更改对象参数是不好的做法吗? [英] Is mutating object-parameters in a method(in Java) a bad practice?

查看:98
本文介绍了在方法(在Java中)中更改对象参数是不好的做法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个关于在方法中对方法参数(即对象)进行变异的问题.

I have a question about mutating method-paramaters(which are objects) in a method.

我多次听到并听到,以参数形式传入的方法对对象进行变异是一种不好的做法.例如:

I read and heard multiple times that it is a bad practice to mutate a object in a method which was passed in as a paramater. As example:

public void modifyList(List<Object> list) {
    list.add(new Object());
}

相反,应该复制传入的Object,对复制的对象执行变异,并应返回复制的对象.例如:

Instead, the passed in Object should be copied, the mutation should be performed on the copied object and the copied object should be returned. As example:

public List<Object> getModifiedList(List<Object> list) {
    List copy = new List<Object();
    //Make a deep copy if it would be necessary
    for(Object o : list) {
        copy.add(o.clone());
    }
    //Modify the copy
    copy.add(new Object());
    //return the copy
    return copy;
}

我知道第二种方法产生副作用的可能性较小,因为它不会改变输入参数.

I understand that the second method has less potential for side effects because it doesn't mutate the input parameter.

但这真的是要走的路吗?由于必须创建许多深层副本,因此性能会受到影响.同样,为所有类实现Copy-Constructors和实现克隆方法也将花费大量时间.同样,它将增加LOC的数量.

But is this really the way to go? The performance would suffer because a lot of deep copys have to be created. Also it would cost a lot of time implement Copy-Constructors and implement clone-methods for all classes. Also it would increase the LOC immense.

实际上,我不经常看到这种模式(复制方法参数).

In practice I don't see this pattern(copy the method-parameter) often.

具有丰富经验(多年作为程序员/软件开发人员)的人可以回答这个问题吗?

Could somebody with a lot of experience(working as a programmer/software developer for years) answer this?

问候 小牛

推荐答案

两种方法都很好,根据您的用例,可能是正确的选择.只需确保以一种清晰易懂的方式命名它们并编写一些Javadoc.

Both methods are fine and could be the correct choice depending on your use case. Just make sure that you name them in a way that makes the intent clear and write some javadoc.

然后由开发人员来决定是否可以更改原始列表,如果没有,则通过副本或使用其他方法.

It's then up to the developer to decide whether having the original list mutated is ok or not, and if not, pass a copy or use a different method.

例如,此方法会更改现有列表,但其意图和文档非常清楚.

For example, this method from the JDK mutates an existing list, but its intent and documentation are very clear.

这篇关于在方法(在Java中)中更改对象参数是不好的做法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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