0

I've been playing with the Immutables Java library for a while and I was wondering if there's any way of making defensive copying. Please consider the following code:

@Value.Immutable
public interface Employee {
  String getName();
  Integer getAge();
  Address getAddress();
}

public class Address {
  public String street;
  public String building;
  public int postalCode;

  // Constructor here...
}

Address fields are explicitly public for this scenario. After initializing the Employee with:

Employee immEmployee = ImmutableEmployee.builder()
        .name("John")
        .age(35)
        .address(new Address("Sesame", "Plaza", 123))
        .build();

I get an output of Employee{name=John, age=35, address=Address{street='Sesame', building='Plaza', postalCode=123}}.

But when I do:

immEmployee.getAddress().postalCode = 456;

I will get Employee{name=John, age=35, address=Address{street='Sesame', building='Plaza', postalCode=456}}.

As you can see the original referenced object's state which is the Address postalCode value was changed. I would like to retain the original object's state and just return a new copy whenever someone tries to modify the referenced object state. Thank you for your inputs.

akatsuki
  • 27
  • 8
  • Is it an option to make `Address` an immutable class? If not, then I think you should rather look at solutions for cloning generic instances. – Henrik Aasted Sørensen Oct 13 '22 at 12:45
  • @HenrikAastedSørensen - thank you for your comment. It's not an option as in this scenario, `Address` is a read-only class (probably a library) and cannot be modified. – akatsuki Oct 14 '22 at 22:00

0 Answers0