the good way of returning a mutable object

Viewed 22855

Let's say I have a class Comment and I have a private field named commentDate which is a java.util.Date and with a getter named getCommentDate.

Why it's better to return a copy of that date ( return new Date(commentDate.getTime()) ) than simply returning that date...

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

8 Answers

Note: Do not return mutable objects via getters eg. date (before Java 8). It can always be reset by a rogue programmer. Lets say you write a program where social security benefits of an employee is calculated based on the years of work.

public class Employee {
// instance fields
private String name;
private String nickName;
private double salary;
private Date hireDay;

// constructor
Employee(String name, String aNickName, double aSalary, int aYear,
        int aMonth, int aDay) {
    this.name = name;
    nickName = aNickName;
    salary = aSalary;
    GregorianCalendar cal = new GregorianCalendar(aYear, aMonth - 1, aDay);
    hireDay = cal.getTime();
}
//needs to be corrected or improved  because date is a mutable object
public Date getHireDay() {
    return hireDay;
}

A hacker/bad programmer can reset the date using a setter

Employee john = new Employee("John", "Grant", 50000, 1989, 10, 1);
    Date d = john.getHireDay();

    // Original hire date is Oct 1, 1989
    System.out.println("Original hire date "+ d.getTime()));

    long tenYearsInMilliseconds = 10 * 365 * 24 * 60 * 60 * 1000L;
    long time = d.getTime();

    // Hire date after hacker modifies the code
    d.setTime(time - tenYearsInMilliseconds);
    System.out.println("Hacked hire date "+john.getHireDay().getTime()));
}

Instead..return a clone of the date method for Java 7 or use LocalDate Class for Java 8

 // for Java 7
public Date getHireDay() {
    return (Date)hireDay.clone();
}

//for Java 8
public LocalDate getHireDay() {
    return hireDay;
}
Related