This week's book giveaways are in the Java EE and JavaScript forums.
We're giving away four copies each of The Java EE 7 Tutorial Volume 1 or Volume 2(winners choice) and jQuery UI in Action and have the authors on-line!
See this thread and this one for details.
The moose likes Java in General and the fly likes Equal immutable objects Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Equal immutable objects" Watch "Equal immutable objects" New topic
Author

Equal immutable objects

Yosi Hendarsjah
Ranch Hand

Joined: Oct 02, 2003
Posts: 164
When do we need to create two or more equal immutable objects?
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24183
    
  34

Well, generally, never, at least not knowingly. But to avoid it, you usually need a cache of all the objects you've created, and keeping the cache, and searching through it to find the appropriate object to reuse, can be more computationally expensive than creating a new one -- at least for small, simple objects.


[Jess in Action][AskingGoodQuestions]
Sumitro Palit
Ranch Hand

Joined: Dec 13, 2003
Posts: 37
Yosi,
Just as Ernest suggested, you might want to have some logic to avoid such scenarios. In that case, you might want to encapsulate the class creation logic in a class factory and not instantiate the objects directly. This might be overkill for simple projects but certainly worth the pain if you have to apply complex logic to determine the class/subclass that you need to create under certain preconditions and dont want to repeat the logic everywhere. There is more to the factory pattern, but you might use it to yor advantage in situations like this too.
Kindof like:
instead of doing :
MyObject o = new MyObject(params...);
do:
MyObject o = MyObjectFactory.CreateMyObject(params...);
CreateMyObject will contain the logic of determinining a valid MyObject to return.
-ortimus
"Simplicity is virtue"
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
 
subject: Equal immutable objects