Search code examples
javaimmutabilityimmutables-library

Mutable items in Immutable


When we create immutable classes using the Immutable objects library, how can we handle mutable members (e.g. j.u.Date)?

NOTE: this is not about the java Date class and totally related to the Immutable Objects java library which will generate some code!

Example:

@Value.Immutable
public interface MyImmutableClass {
    Date creationDateTime();
}

Is there a way to override the getter, so that it returns a copy?

public Date creationDateTime() {
    return new Date(creationDateTime.getTime());
}

Solution

  • From my question in the Immutables issue tracker I learned that the cleanest way to handle mutable objects is to use a custom encoding annotation.

    I've created a little open source project tmtron-immutables encoding to create such an annotation for the java.util.Date class. This should be a good starting point for anyone who wants to create a custom encoding.

    Then you can directly use your mutable class (e.g. java.util.Date) as attribute and still get the same immutability guarantee as for immutable attributes (like String, long, etc.)

    @Value.Immutable
    @DateEncodingEnabled
    public interface ValueObject {
        Date creationDate();
    }
    

    The @DateEncodingEnabled annotation will make sure that only the immutable long value of the Date object is stored in the ImmutableValueObject class.