I have domain object User which contains simple value object 'Contact'. Contact contains only getters without setters.

public class User {
    private Contact contact;
// other methods and fields

public class Contact {
    private String phone;
    private String email;
    private String fax;
// and geters

I need to update user's contact. I have two ways to do this, but I don't know which is better. Does domain object should allow to assign reference from outside? But on other hand creating new object maybe is overuse.

public void updateContact(Contact newContact) {
    this.contact = newContact;

public void updateContact(Contact newContact) {
    this.contact = new Contact(newContact.getEmail(), newContact.getFax(), newContact.getPhone());

Well you're not dealing with a soft or weak reference, so there is no reason to assume that the instance of newContact being passed cannot be retained. More importantly, there are no setters on Contact, which strongly implies that Contact is immutable. This isn't to say it can't be forcibly changed, though doing so would almost certainly be wrong.

Therefore, if you assume Contact is immutable, you would not be at fault for doing so, and you should be safe simply assigning your contact to newContact being passed (your first updateContact method).

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.