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.
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