Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to define a mutable object? #41

Open
deanwong opened this issue Oct 12, 2015 · 3 comments
Open

How to define a mutable object? #41

deanwong opened this issue Oct 12, 2015 · 3 comments

Comments

@deanwong
Copy link

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

@Cs4r
Copy link

Cs4r commented Oct 12, 2015

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
Copy link
Author

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
Copy link

Cs4r commented Oct 13, 2015

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants