nihilon
nihilon

Reputation: 834

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 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?

Upvotes: 2

Views: 131

Answers (2)

Michael Humelsine
Michael Humelsine

Reputation: 601

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.

Upvotes: 1

La-comadreja
La-comadreja

Reputation: 5755

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.

Upvotes: 2

Related Questions