0

I have a scenario wherein I have associated a collection of Model object against an identifier[BASE]. As per my business use case I can create a scenario from the identifier[BASE]. In that case the collection on model object is also referred to. Doing so I dont need to create snapshots of same data again.

Another use case is that user might modify some value in the derived scenario from identifier[BASE]. In this case, Model object corresponding to the modified value will be replaced with new Model object.

This scenario might happen as many times wherein my whole collection of Model objects might be replaced by new objects.

My question is that the approach of creating a new immutable object and replacing it in the reference everytime user modeifies anything is appropriate or not.

Or could there be another better approach, wherein whenever user modifies the object instead of returning a new immutable object we should return a new mutable object which can further be mutated as many times as required by user. This would also ensure that the initial collection of Model objects is not mutated.

Any thoughts.

TIA!

user1441849
  • 245
  • 3
  • 10
  • 4
    If you could give an example of what you want to do, it would be very helpful.. Frankly I am not getting your question.. Are you using a Map kind of structure to map base ids to objects? – TheLostMind Feb 27 '15 at 05:56
  • Check out http://docs.oracle.com/javase/tutorial/essential/concurrency/immutable.html and http://programmers.stackexchange.com/questions/151733/if-immutable-objects-are-good-why-do-people-keep-creating-mutable-objects – Adrian Leonhard Feb 27 '15 at 07:37
  • If you are unsure what immutable means, see http://stackoverflow.com/questions/3162665/immutable-class – Raedwald Feb 27 '15 at 08:15

2 Answers2

2

There is never any reason to clone immutable objects. Because they are immutable it is safe to share them. Copying one would be a waste of memory.

Raedwald
  • 46,613
  • 43
  • 151
  • 237
  • I wouldn't say "never". The [clone method documentation](http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#clone%28%29) says it's "usually" not necessary to clone immutable fields. You may need to clone in cases where you are using the immutable objects identities for comparison. – kapex Feb 27 '15 at 08:54
0

I have used Copyconstructor to copy the object and override any values that I want to. Thus, whenever it is required to modify the object, I create a new object based on existing object with updated values using copy constructor.

user1441849
  • 245
  • 3
  • 10