Search code examples
javaperformancescalaimmutabilityimmutable-collections

Update immutable object without breaking immutability


how can I get updated immutable object from another immutable object without breaking the immutability in a good way. Something similar to how things are achieved in Scala or how they are achieved in Immutables library.

How can I achieve something like Customer.Builder.from(anotherCustomer).replaceOrder(oldOrder,newOrder).with(newName).build()

To reuse the old objects and queue all the changes I want in order to construct a new one.

I am using Java.


Solution

  • public class Customer {
        private String name;    
        private Order order
    
        private Customer(CustomerBuilder builder) {
            this.name = builder.name;
            this.order = builder.order;
        }
    
        public Customer replace(Order order) {
            return new CustomerBuilder().name(this.name).order(order).build();
        }
    
        public static class CustomerBuilder {
            private String name;    
            private Order order
    
            public CustomerBuilder name(String name) {
                this.name = name;
                return this;
            }
    
            public CustomerBuilder order(Order order) {
                this.order = order;
                return this;
            }
    
            public Customer build() {
                return new Customer(this);
            }
        }
    }