This week's book giveaway is in the Other Languages forum.
We're giving away four copies of Functional Reactive Programming and have Stephen Blackheath and Anthony Jones on-line!
See this thread for details.
Win a copy of Functional Reactive Programming this week in the Other Languages 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: 20669
65
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: 50268
80
  • 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