bad programming practice to alter passed objects in java [closed]

爷,独闯天下 提交于 2019-12-23 17:09:08

问题


I was just reading this stack question:

Is Java "pass-by-reference" or "pass-by-value"?

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");
}

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?

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

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!


回答1:


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. the object to change itself (e.g. via a setter setName())
  2. immutability and to create a new modified object where practical



回答2:


Actually, this is the intended behavior of Java. In methods, you can just change states of an object, but not an object itself. So for sure it's not a bad practice.

It all comes down to what is your use case and what do you need to do with your method. The best example of this are setter methods that are part of every bean object.

If your method looks like:

static void changeName(Person anotherReferenceToTheSamePersonObject) {
    anotherReferenceToTheSamePersonObject.setName("Jerry");
    // you change the state of the object on heap you passed in
}

You can alter the state of person object

Person person= new Person("John");
changeName(person);
System.out.println(person.getName()); // prints Jerry

But if the changeName would look like:

static void changeName(Person anotherReferenceToTheSamePersonObject) {
    anotherReferenceToTheSamePersonObject= new Person("Jerry")
    // you assign a new object to a reference-copy - nothing happens to John object on heap
}

Person person= new Person("John");
changeName(person);
System.out.println(person.getName()); // prints John


来源:https://stackoverflow.com/questions/17655639/bad-programming-practice-to-alter-passed-objects-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!