better-java icon indicating copy to clipboard operation
better-java copied to clipboard

How to define a mutable object?

Open deanwong opened this issue 10 years ago • 3 comments

If we always use imitable object, how to change one filed value in this object? copy a instance ?

deanwong avatar Oct 12 '15 07:10 deanwong

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);

Cs4r avatar Oct 12 '15 10:10 Cs4r

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?

deanwong avatar Oct 13 '15 01:10 deanwong

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

Cs4r avatar Oct 13 '15 07:10 Cs4r