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.
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);
}
}
}
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","")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With