Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 693
Alexander Petrov Avatar asked Mar 13 '23 17:03

Alexander Petrov


2 Answers

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);
        }
    }
}
like image 117
Gab Avatar answered Mar 16 '23 00:03

Gab


I recommend this book who cover the subject : https://www.amazon.ca/Effective-Java-Edition-Joshua-Bloch/dp/0321356683

Best way I know to update immutable object is to return modified copy of the object, like java String

    String uppercase = "hello".toUpperCase()

I make easy to use fluent typing

    String uppercasewithoutletterL = "hello".toUpperCase().replace("L","")
like image 44
Saloparenator Avatar answered Mar 16 '23 00:03

Saloparenator