Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Immutable Class

 
jose chiramal
Ranch Hand
Posts: 266
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The following have to be followed for creating an Immutable class:

• Make all fields private
• Don't provide mutators
• Ensure that methods can't be overridden by either making the class final (Strong Immutability) or making your methods final (Weak Immutability)
• If a field isn't primitive or immutable, make a deep clone on the way in and the way out. (I did not understand this point, can someone please clarify this ?)
 
Wouter Oet
Saloon Keeper
Posts: 2700
IntelliJ IDE Opera
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
An example with Date
 
Rob Spoor
Sheriff
Pie
Posts: 20532
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The solution of course is to make copies both in the constructor and in the getter method:
 
jose chiramal
Ranch Hand
Posts: 266
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
All fileds should be private or private final ??

Since immutable means something that cannot be changed ?

 
Campbell Ritchie
Sheriff
Pie
Posts: 48976
60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Fields should usually be private anyway, so you would want private and final for an immutable class.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic