1) Do not provide "setter" methods.
2) Make all fields final and private
3) Do not let subclasses override methods. Declare class as final
4) For mutable instance variables - Ex date: In this case, special attention should be paid.
5) Make the constructor private and create instances in the factory methods. Factory method of storing the logic of creating an object in one place.
public static MyImmutableClass createNewInstance(Integer fld1, String fld2, Date date) { return new MyImmutableClass (fld1, fld2, date); }
6) Instead, a new Date object should be returned with the content copied to it.
public Date getDateField() { return new Date(dateField.getTime()); }
- Here, dateField is a field that is set inside a private constructor
source share