Would it be overhead to always return a copy of collection/object field?
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:
String.list.get(int), Iterator.next().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.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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With