Stack Overflow Asked on December 20, 2021
For example, if we have a class and one of its method returns an object, we should return a deep copy of the object.
For example, before returning an array of integers, we should also make a deep copy/clone the array before returning it.
Is this also the case for an array of Objects? For example I have an array of objects of type packages:
//trunk[] is an instance variable array that contains objects of type Package in this class
//method to return array
public Package[] getTrunk() {
Package[] temp = new Package[trunk.length];
for(int i = 0; i < trunk.length; i++) {
temp[i] = trunk[i];
}
return temp;
}
Is there any use of using the for loop here since objects are reference types? If not, how should I return the array correctly?
If you return the trunk array, the caller can modify the trunk array. If you return a copy of the trunk array, the caller cannot modify the trunk array.
Do you care whether the caller can modify the trunk array?
The answer to that in part depends on who the caller is. If it's my code calling my code, and I know I'm not modifying the array, just looking at it and not even retaining a copy, then returning the actual array may be fine. Not every interface needs to be idiot-proof; idiot-proofing has a price tag.
(I see this is a 'public' interface but that might just mean a multi-package pre-module product structure)
To my mind, you shouldn't worry about some mythical "best practice", you should worry about how you want the software to behave.
Answered by user13784117 on December 20, 2021
There is no difference between an array of primitives and an array of complex types (Objects of some kind) regarding this question. So in general you can say, yes, you should only return a copy.
But there are some exceptions where not returning a copy may be the intended, because:
Answered by Felix on December 20, 2021
Get help from others!
Recent Questions
Recent Answers
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP