lundi 12 janvier 2015

Immutable objects with Mutable fields


Vote count:

0




The Setup: I am attempting to write a value object, so I figured it would be best to make it immutable. This object has a BigDecimal, so:



public class MyValueObject {
private final BigDecimal bob;

public MyValueObject() {
bob = new BigDecimal(0);
}
}


I have also written a handful of methods, including an add method, that return new MyValueObjects. Here is an example of one:



public MyValueObject add(BigDecimal augend) {
return new MyValueObject(this.bob.add(augend);
}


The question is, does this effectively set bob or is it returning a completely new MyValueObject with an entirely new BigDecimal as expected?



asked 2 mins ago


1 Answer



Vote count:

0




If you use "new", you are creating a new object. So It is returning a completely new MyValueObject which utilizes "bob", but is not the same.



answered 41 secs ago






Immutable objects with Mutable fields

Aucun commentaire:

Enregistrer un commentaire