user321068
user321068

Reputation:

Good practice to edit objects "by reference"?

Let's say I've got a type called Superstar. Now I want to have a method that does some work and edits some properties of a Superstar object.

Here are two ways of how I could implement this. Way 1 would be the following:

private Superstar editSuperstar(Superstar superstar){
    ....
    superstar.setEdited(true);
    return superstar;
}
...
superstar = editSuperstar(superstar);

And way 2 would be this:

private void editSuperstar(Superstar superstar){
    ....
    superstar.setEdited(true);
}
...
editSuperstar(superstar);

Which one of these two possible ways is considered "best practice"? The first one, or the second pseudo "by reference" one?

Upvotes: 12

Views: 4252

Answers (5)

atamanroman
atamanroman

Reputation: 11808

The first form would be surprising for the API clients if you return the same instance having only changed some fields. One would expect to get a modified copy back without having the original instance changed.

So use the second form if you don't return a copy and use the first if you do (and think about making Superstar immutable in that case).

Upvotes: 1

pgras
pgras

Reputation: 12770

The problem you have here with first method is if you use it like that:

Superstar edited = editSuperstar(originalSuperstar);

This will also modify the originalSuperstar which is, in my opinion, counterintuitive...

Thus prefer the second one if you modify the passed object or the first one if you return a new copy of the object.

For this peculiar example you could simply add an edit method to the Superstar class...

Upvotes: 2

Marcelo Cantos
Marcelo Cantos

Reputation: 185852

The first form is deceptive. It gives the impression that one object is being passed in, which is copied and the copy then altered and returned.

"Best practice" would be to use the first form, but to actually do what is implied (apply the change to a copy, which is then returned). Immutable objects should generally be preferred over mutable objects unless they are big chunky things that are expensive to copy, in which case, you should then favor the second form.

Upvotes: 4

Michael Aaron Safyan
Michael Aaron Safyan

Reputation: 95449

Use way 2 unless you are creating a "builder" class where you intend to chain invocations. Ex:

MyClass c = (new MyClassBuilder()).setX(blah).setY(blah).build();

Upvotes: 4

Riduidel
Riduidel

Reputation: 22292

In your case, the second form is preferrable, as you directly change one of you superstar properties (edited). However, if you have a method that use a superstar object and returns an updated version of it (without changing the initial one) the first form will have my favor.

Finally, since both of this examples only use Superstar object, they should be member methods of the Superstar class.

Upvotes: 6

Related Questions