简体   繁体   中英

Immutable objects with Mutable fields

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 MyValueObject s. 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?

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.

I didn't have a Java editor around so forgive the example. Sometimes it is kind of useful to use a static "builder" in cases like this and make the constructor private.

public class ValueObject {
    private int bob;

    private ValueObject(int bob) {
        this.bob = bob;
    }

    public static ValueObject Create(int value){
        return new ValueObject(value);
    }

    public ValueObject Add(int increaseBy) {
        return ValueObject.Create(this.bob + increaseBy);
    }
}

I realised I didn't answer the question. You would be creating a new object. My answer was intended to make the "creating" more clear in the code which will make it more clear to you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM