0

I know that Java passes objects by value, but you can still do stuff with an object that is being passed to the function. So I'm not sure which way is more preferable and, um, cleaner, if I want to do something to an object in my function. Should I just change it like this:

public void foo(Person person){
    person.setName("John");
}

or should I explicitly return the object like this:

public Person foo(Person person){
    person.setName("John");
    return person;
}

The result is the same in both cases, but which one is safer? Or is there no difference?

graynk
  • 131
  • 1
  • 2
  • 17
  • In both cases, you're modifying the object referenced by the reference value you passed. Why do you need to return that value? – Sotirios Delimanolis Jun 23 '15 at 15:21
  • In fact the object reference is passed by value – Michael Laffargue Jun 23 '15 at 15:22
  • Code readability, I guess. For example - if I want only to read values then I use void, if I change an object - I return it, so it's obvious that the function does something to it. Something like that. That's my question - is there a reason to return it at all? Due to "good style of programming" or anything like that – graynk Jun 23 '15 at 15:26
  • There is no reason to return it at all, unless the object that you are passing to the method is immutable, in that case you would return the modified object. For this example treat the person object passed to the foo method as a dependency of the calling method and you are fulfilling it by passing the object. – Johnson Abraham Jun 23 '15 at 15:29
  • Some of the `String` class' methods have a return type of `String`, doesn't mean they do anything to the `String` itself or any passed in as an argument. In fact, they don't. Strings are immutable. A return type is a poor indication of anything other than to indicate the fact that a value of that type is returned. – Sotirios Delimanolis Jun 23 '15 at 15:29

0 Answers0