简体   繁体   中英

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?

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.

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();

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.

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...

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM