cxxr / better-java

Resources for writing modern Java
Other
5.79k stars 730 forks source link

How to define a mutable object? #41

Open deanwong opened 8 years ago

deanwong commented 8 years ago

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

Cs4r commented 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);
deanwong commented 8 years ago

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?

Cs4r commented 8 years ago

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