Change object in another method

Asked

Viewed 658 times

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 ?

  • 2

    Who says? Name a source of this.

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

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

1 answer

2

It is not a rule, you can make changes to a past object because it is just a "pointer". Just be careful in the libraries and Apis you’re using.

For example, suppose a JPA/Hibernate project, with the following code:

 public void updateEmployee(Employee emp) { 
    entityManager.merge(emp);
    emp.setLastAccessTime(new Date());
 }

The new instance of new Date() will be persisted in the database when the context of that transaction ends?

It will not be persisted! Because the method object merge(object) returns an instance that is in the persistent context and not in Detached. Thus, the object passed as a parameter continues not talking to the JPA persistent context, but only its return. So for the code to persist the new date would need to make a small change in the code.

 public void updateEmployee(Employee emp) { 
    Employee empDB = entityManager.merge(emp);
    empDB.setLastAccessTime(new Date());
 }

That way when the transaction ends the new Date instance will be persisted.

I hope it helped!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.