Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Immutable class design

Tags:

java

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?

like image 410
Cheok Yan Cheng Avatar asked Aug 01 '10 16:08

Cheok Yan Cheng


1 Answers

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.

like image 70
jqno Avatar answered Oct 01 '22 22:10

jqno