Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deep copying in getters for mutable object [closed]

Tags:

java

oop

Would it be overhead to always return a copy of collection/object field?

like image 387
Alexey Galanov Avatar asked Oct 23 '25 15:10

Alexey Galanov


2 Answers

Clearly, yes it would be a overhead ... compared with returning a reference or a shallow copy.

But that's not really the point. The real point is whether the overhead is warranted / necessary, and whether it can be avoided by using some other data structure / design / technique. The answer to those questions depends on the context.


Here are some illustrations:

  1. If a target object getter returns an immutable object, a copy is unnecessary. Example, any getter that returns a String.
  2. If a target object getter returns an object that is not part of the target object abstraction, a copy is undesirable. Example list.get(int), Iterator.next().
  3. If a target object getter returns a mutable object (or array) AND the returned object is part of the object's internal state AND the target doesn't necessarily trust the caller, then the getter should either copy it or wrap it ... or there may be a security problem.
  4. The same may apply in non-security-related contexts; e.g. ArrayList.toArray(...) copies the list into an separate array rather than returning the list's backing array. (Similar for getChars() for a String, StringBuffer, etc.) This is all about maintaining the abstraction boundary so that on class won't "break" another one.
  5. If a target object getter returns a mutable object (or array) AND the returned object is part of the object's internal state BUT the target object's API / abstraction boundary is designed to be "porous" (e.g. for performance reasons), then copying may be self defeating.

Of these, 3 is the only case where cloning is strictly mandatory. In 2, 4 and 5 you could argue that it is a matter of how you design the public (or internal) APIs for the classes, libraries, applications. And often there are many viable choices.

like image 97
Stephen C Avatar answered Oct 26 '25 03:10

Stephen C


It is overhead for sure but there are already some framework classes which do that. It is also described in the book Effective Java.

Remember:

"Classes should be immutable unless there's a very good reason to make them mutable....If a class cannot be made immutable, limit its mutability as much as possible."

When you want to create immutable classes than you can use a framework like that: http://immutables.github.io

For examples check this Oracle documentation

like image 33
Kevin Wallis Avatar answered Oct 26 '25 05:10

Kevin Wallis



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!