Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return immutable copy of mutable object from method

I have some closed component which is working over some XML object. I need to expose this object outside of this component, but I don't want to allow changes on it outside of my component. How can I complete this?

like image 370
bel Avatar asked Jul 07 '26 00:07

bel


1 Answers

Ensure your object has a copy constructor that allows you to make a deeply-cloned copy of your class.

Then call this when you return the object, e.g.

SomeClass instance = // ....


public SomeClass getInstance() {
  return new SomeClass(instance);
}

This won't make the returned object immutable. But it doesn't need to be - you just don't want the external code making changes to your copy of the data.

like image 145
Duncan Jones Avatar answered Jul 08 '26 14:07

Duncan Jones



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!