I am creating several functions in which I want to return the interface instead of the implementation, I.E. List instead of ArrayList . My method signature and a brief implementation follows:
public List<MyAwesomeComposedObject> convert(Collection<MyAwesomeObject> awesomeObjects>)
{
List<MyAwesomeComposedObject> composedObjects = new ArrayList<MyAwesomeComposedObject>();
for(MyAwesomeObject awesomeObject : awesomeObjects)
{
MyAwesomeComposedObject composedObject = new MyAwesomeComposedObject(awesomeObject);
composedObjects.add(composedObject);
}
List<MyAwesomeComposedObject> composedObjectList = Collections.checkedList<composedObjects, MyAwesomeComposedObject.class);
return composedObjectList;
}
My question is, is this an antipattern of some sort? I want to guarantee that the invoker of this method is getting the interface instead of an implementation. I also do not believe this to be a case of overengineering. If this is not the correct way to return an interface, in this scenario I am open to the correct implementation.
Attached is a small program that results in an exception:
public static void main(String[] args)
{
Vector v = (Vector) c();
}
static List<Object> c()
{
List<Object> l = new ArrayList<Object>();
l.add(new Object());
List<Object> o = Collections.checkedList(l, Object.class);
return o;
}
The javadoc is here: checked list
For your revised question: There is no way to prevent the caller from attempting to cast to whatever they want. If it is an inappropriate cast they will get the exception. This is the very reason why casting from an interface to a concrete class is strongly discouraged.
If you are really worried about this, consider returning an
ArrayListinstead of aList. That should discourage casting since they are getting a concrete type. Please note that I do not endorse this, it is just an option.This is not valid. You are returning a
Listwhere the declared type of the elements is an interface, however each element must be SOME instantiation. All a checked collection does is prevent the addition of elements of the incorrect type. There is nothing that prevents the user from casting back to the implementation type.If you are attempting to ensure that the user gets
Listinstead ofArrayList(my assumption here because I don’t see an interface for you Awesome class), this again is flawed because the user could still cast theListto anArrayListalthough this would be a bad idea since it risks aClassCastException.