One of the advice given by Joshua Bloch is that, class should be designed as immutable.
I have the following class
public class Dividend {
public Dividend setDate(SimpleDate date) {
Dividend dividend = new Dividend(this.getStock(), this.getAmount(), date);
return dividend;
}
.....// More to go.
For setDate method, this object will not be modified.
Instead, a clone copy of this with its date field being modified will be returned.
However, by judging from the method name, how does the user will know this object will still remain immutable?
Is there a better naming convention besides setDate?
If you have setters, your class will look mutable, and users will probably use it the wrong way. They'll probably call it like this:
dividend.setDate(myDate);
And then be surprised why the dividend
's date didn't change. They should have used it like this:
newDividend = dividend.setDate(myDate);
To make the API more intuitive, it would be better to rename the setDate
method to something like copyWith
:
newDividend = dividend.copyWith(myDate);
Or, if you have many fields and overloading would be confusing, you could call them copyWithDate
and copyWithComment
.
Other names are possible too, as stated in the other answers: derive
(and deriveWithDate
), or simply withDate
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With