I have come across a class that has an immutable property:
MyObject[] allObjs
The property is initialized like this:
List<MyObject> objs = createAllMyObjects();
allObjs = objs.toArray(new MyObject[objs.size()]);
When it is exposed through the accessor, it's done as a List:
public List<MyObject> getAllMyObjects() {
return Collections.unmodifiableList(Arrays.asList(allObjs));
}
Why would a programmer do this? Is there a benefit that I don't know about?
Performance is not a concern, as the array of objs will only ever number in a few dozen elements.
It seems that we are going round and round in circles.
The class is a sort of factory, so it's got a private constructor and exposes only static methods (not sure if this could be a reason for the madness).
edit
I guess that my question is really, "Why not just use an internal List<MyObject> allObjs
instead of MyObject[] allObjs
, and return the Collections.unmodifiableList(allObjs)?" as this would accomplish the same thing.
The only reason I see is "fail early in case of misuse" (if this design choice was not random and has a meaning, the meaning is he trusts very little his particular clients).
MyObject[]
is reified, and checked at runtime, while List<MyObject>
is not. One can sneak non-MyObject references in the latter (he'll get unchecked warnings at compilation of course), which will fail at some undefined future point with a ClassCastException
, but he cannot do the same with MyObject[]
- that will fail immediately at the point of misuse.
Note though that if the clients are prebuilt binaries that was using this API before it was generified, then nobody got unchecked warnings, so if this code is trying to migrate code used by pre-generics clients, it makes sense.
(Another way to achieve the same result would be using List<T>
and also requiring Class<T>
, so that the latter can offer the runtime type checks. But that would require for example another constructor parameter - existing clients wouldn't automatically take advantage of that. **Update: ** This basically describes the API call mentioned in the first comment by Sauer, so one does not have to reinvent this, just use that one :) ).
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