a) Then you miss some adventages of OO programming and the values of the class can still be changed.
b) Then there can only be one object
c) I would go for that one. And make the properties final.
"Any fool can write code that a computer can understand. Good programmers write code that humans can understand." --- Martin Fowler
Please correct my English.
Joined: Jan 16, 2003
kri shan wrote:Converting value objects into Immutable class:
a). Make class as final.
b). all the methods and properties are static final.
c). private properties with getter methods, but without setter methods.
Which is best approach for Immutable Value objects ?
An immutable object is nothing more than an object who's encapsulated data cannot be modified, such as the java.lang.String class. Just pass all data into the contructor and provide only getter methods. You must also make all getter methods return copies (deep clones) of the object values encapsulated within you class. If you do not return a copy then the client of your object can change your encapsulated data just by changing the data in the object they received from the getter method.
By the way, years ago the term "value object" use to refer to an immutable object. I think it was Sun who started using the term "value object" as most developers do now.