the good way of returning a mutable object

How can a user change the object state of that Date since it's a getter, not a setter?

Easily:

Comment comment = new Comment();
comment.getCommentDate().setTime(0); // now it's January 1, 1970 00:00:00 GMT.

First off, please, please, please avoid using getters and setters as much as possible. If you have both of them for the same field you are almost certainly doing something wrong. I don't care what the Java gurus are telling you. They don't know what they're talking about. This is not how OO works. OO is not a make-work project to turn field accesses into method calls. That doesn't actually encapsulate anything.

That said: if you return the date itself, then the calling code has a reference to your date object, and can use its full interface. Since dates are mutable objects, the interface includes things that can change the object state. Since the reference is to your date, your date's state will get changed. It doesn't matter how the calling code got the date (i.e. "with a getter").


Since java.util.Date implements Cloneable you can easily clone the date, as:

public class DateTest {
    private Date date;

    public DateTest() {

    }

    public Date getDate() {
        return (Date) date.clone();
    }

    public void setDate(Date date) {
        this.date = (Date) date.clone();
    }       
}

Tags:

Java