Open deanwong opened 8 years ago
Assuming you meant immutable object here is my answer:
If we use an immutable object, each time we want to modify any of its properties we are obliged to create a new instance of that class with the desired values.
I also share with you an example for complementing my explanation.
/* Objects of this class are immutable */
public class MyObject {
private String a;
private int b;
MyObject(String valueA, int valueB){
a = valueA;
b = valueB;
}
public String a() { return a;}
public int b() {return b;}
}
MyObject first = new MyObject("hello", 1);
/* If we want to increase the value of the field 'b' in two units we need to do the following... */
first = new MyObject("hello", first.b() + 2);
Thank Cs4r,
If MyObject has lots of properties, it will have a long construct method and the copy operation seems not clean. Is there any possible to use Dozer or other library to find a better way?
If MyObject has lots of properties, the best thing you can do is to have a Builder in order to avoid telescoping constructors. Please see: https://github.com/cxxr/better-java#the-builder-pattern
If we always use imitable object, how to change one filed value in this object? copy a instance ?