Friday, September 4, 2009

How to make an object immutable?

  • Do not provide any methods such as setters or any methods that may alter the properties of that object. If you do, make sure they return a new instance of your object.
  • All properties and methods of that object are to be marked as final. Marking the methods as final is extremely important. We don’t want anyone carelessly overriding our functions that may compromise our immutable behavior( or making class as final is enough).
  • All properties of that object are to be marked as private
Here is an example:

public final class BudgetData{
private float _budget;
private String _name;
private Date _date;

public (float budget, String name, Date date){
_budget = budget;
_name = name;
_date =new Date(date.getTime());
}

public final (float getBudget() {
return _budget;
}

public final String getName() {
return _name;
}

public final Date getDate() {

return new Date(_date.getTime());
}
}

No comments:

Post a Comment