在java中改变传递对象的不良编程习惯 [英] bad programming practice to alter passed objects in java

查看:43
本文介绍了在java中改变传递对象的不良编程习惯的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是在阅读这个堆栈问题:

I was just reading this stack question:

Java 是pass-by-reference"吗?还是传值"?

我想知道使用一种方法来改变对象的地址是否被认为是不好的编程习惯.我质疑这一点,因为它无疑是 Java 的一个令人困惑的属性.

And I was wondering if it is considered bad programming practice to use a method to alter an object by it's address. I question this because it is no doubt a confusing property of Java.

所以你从上面的问题中得到了这段代码:

So you have this code taken from the above question:

Person person;
person = new Person("Tom");
changeName(person);

//I didn't use Person person below as an argument to be nice
static void changeName(Person anotherReferenceToTheSamePersonObject) {
    anotherReferenceToTheSamePersonObject.setName("Jerry");
}

由于其令人困惑的性质,这似乎在编程中确实需要避免.这通常是一种可接受的 Java 编程方法吗?

It really seems like this is something to avoid in programming because of its confusing nature. Is this typically an acceptable method of Java programming?

(当然,经典的替代方法是使用新名称作为参数调用 person.changeName() 函数.)

(The classic alternative of course being to call a person.changeName() function with the new name as the parameter.)

如果这不适合 Stack,我一定会删除它.我只是对如何在现实世界中使用这种能力感兴趣.它在专业环境中被宽恕吗?谢谢!

If this is not appropriate for Stack, by all means I'll remove it. I was just interested in how this ability is used in the real world. Is it condoned in a professional environment? Thanks!

推荐答案

我当然认为这很令人困惑,而且很大程度上出乎意料.除非该方法明确命名,否则我通常希望该方法不会更改传递的参数.

I certainly think it's confusing and largely unexpected. Unless the method is explicitly named, I would generally expect that the method wouldn't change the passed argument.

我愿意(排名不分先后)

I would favour (in no particular order)

  1. 要更改自身的对象(例如,通过 setter setName())
  2. 不变性并在可行的情况下创建一个新的修改对象

这篇关于在java中改变传递对象的不良编程习惯的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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