Inquisitive
Inquisitive

Reputation: 7856

Why do immutable classes provide mutators?

Consider the following code:

    bdval = new BigDecimal(strval, new MathContext(attrib.getPrecision()));
    bdval.setScale(attrib.getScale(), RoundingMode.HALF_UP);

PMD quite correctly says:

Useless operation on Immutable

So why do Immutable classes like BigDecimal export mutators for properties?

Upvotes: 3

Views: 634

Answers (1)

JB Nizet
JB Nizet

Reputation: 691983

setScale() doesn't mutate the BigDecimal it's called on. It returns a copy of the BigDecimal with the new scale value.

PMD reports an error because YOUR code is wrong: it ignores the result of the operation making the operation useless. Your code should be:

bdval = bdval.setScale(attrib.getScale(), RoundingMode.HALF_UP);

Upvotes: 8

Related Questions