3

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!

Community
  • 1
  • 1
eatonphil
  • 13,115
  • 27
  • 76
  • 133

2 Answers2

2

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
Brian Agnew
  • 268,207
  • 37
  • 334
  • 440
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
darijan
  • 9,725
  • 25
  • 38