This week's book giveaway is in the OCAJP 8 forum.
We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line!
See this thread for details.
The moose likes Java in General and the fly likes Immutable objects. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of OCA Java SE 8 Programmer I Study Guide this week in the OCAJP 8 forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Immutable objects." Watch "Immutable objects." New topic

Immutable objects.

Michael Morris
Ranch Hand

Joined: Jan 30, 2002
Posts: 3451
I read the article Mutable and Immutable Objects in the newsletter and found it very informative. It made me realize how easy it is for an object reference to slip thru the cracks and cause your immutable object to become mutable. What was not addressed in the article though was the use of factory methods to get instances of immutable objects and declaring the default constuctor private. Of course this would only concern classes that were Strongly Immutabe. I've seen it done both ways. If you only have one or two ways to construct a strongly immuatable object doesn't it make more sense to use factory methods to get instances?
Michael Morris

Any intelligent fool can make things bigger, more complex, and more violent. It takes a touch of genius - and a lot of courage - to move in the opposite direction. - Ernst F. Schumacher
David O'Meara

Joined: Mar 06, 2001
Posts: 13459

Yep. Hopefully I'll get this included in the follow up article and in the next newsletter as long as the baby isn't early
Factory methods are great, even better since they can promote instance sharing and the ability to use == comparison, but I find it only really works with relatively simple immutable objects. More complex immutable objects are a different topic, but basically I'm going to say they're combersme and almost unusable without defending my point of view here
Of course 'Enumerated type' types and other types with finite values are also great when accessed as immutables via factories.
Michael Morris
Ranch Hand

Joined: Jan 30, 2002
Posts: 3451
Thanks David. I'm in the middle of redisigning a structural steel detailing application (actually I'm porting everthing to JAVA from a mixture of languages) and have a lot of simple classes that encapsulate values peculiar to that domain space. Most of them are constucted with a single double (oxymoron? ) so I've been using factory methods to get instances.
Michael Morris
I agree. Here's the link:
subject: Immutable objects.
It's not a secret anymore!