How to make defensive copying in Immutables Java library?

66 views Asked by At

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.

0

There are 0 answers