Change object in another method

1

What is wrong with changing an object, which was passed to another method?, eg:

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 do not understand is why return the same instance of the changed object? Some say that this is less prone to errors, because in the first way you end up losing the "trace" of where the object is being altered. Honestly this argument did not convince me.

Is there any "good practice" for such cases, or is it really an ideological developer issue?

    
asked by anonymous 20.02.2015 / 19:04

1 answer

2

It is not a rule, you can make changes to a past object because it is just a "pointer". Just beware of 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());
 }

Will the new instance of new Date() be persisted in the database when the context of this transaction ends?

It will not be persisted! Because the object merge(object) method returns an instance that is in the persistent context and not in detached. Thus, the object passed as a parameter is still not talking to JPA context persistence, but only its return. So for the code to persist the new date would be necessary 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 instance of Date will be persisted.

I hope you have helped!

    
21.02.2015 / 01:18