1
What’s wrong with changing an object, which has been passed to another method ? , e.g.:
public void doSomething(User user){
edit(user);
//...
EntityManager.persist(user);
}
public void edit(User user){
//...
user.setName("new name");
}
In general everyone says that the form below would be the "most correct"
public void doSomething(User user){
User updatedUser = edit(user);
//...
EntityManager.persist(updatedUser);
}
public User edit(User user){
//...
user.setName("new name");
return user;
}
But what I don’t understand is why return the same instance of the altered object ? Some say that this is less prone to errors, because in the first way you end up losing the "trace" from where the object is being altered. Honestly not that argument didn’t convince me.
Is there any "good practice" for such cases, or would it even be an ideological issue of developer ?
Who says? Name a source of this.
– Maniero
@bigown Actually this is something I’ve been hearing from some people during my career, and only today I decided to question this question in more detail.
– Josh
Whenever someone says something ask why. Ask the person to show you the reason for it. In many cases she’s just repeating what she’s heard from someone else who’s doing the same thing until she gets to someone who’s invented some crazy thing. Ask right away when someone throws up a rule for you.
– Maniero