Why is the following seen as better than the old way of casting?
MyObj obj = someService.find(MyObj.class, "someId");
vs.
MyObj obj = (MyObj) someService.find("someId");
Why is the following seen as better than the old way of casting?
MyObj obj = someService.find(MyObj.class, "someId");
vs.
MyObj obj = (MyObj) someService.find("someId");
There's no guarantee that the non-generics version will return an object of type 'MyObj', so you might get a ClassCastException.
In case 1, most well-implemented services would be able to return null if there no object with id someId
of type MyObj
could be found. Moreover, the first case makes it possible for the service to have some specific logic particular to working with classes of type MyObj
.
In case 2, unless you use instanceof (avoid if possible), then you are risking a ugly ClassCastException
which you would have to catch and handle.
One reason why first scenario is better is that the find(Class,String)
method now has knowledge of what its return value is being assigned to. Therefore, it is now capable of doing any relevant casts internally instead of simply hoping the correct type was returned. For example, suppose the find
method locates a String
object internally when called with "someId"
. The find
method may have a strategy for casting a String
to a MyObj
instance.
Another advantage to using an explicit type parameter would be to allow the service method to be implemented using a Proxy
(in this case MyObj
would need to be MyInterface
). Without explicit type parameters, this would not be possible.
You might use a Proxy
under the covers for many reasons (testing for one)