Reputation: 6032
I have few cases when I always use casting and would like to know if I can actually avoid them?
1. Consider interface from sf - org.springframework.validation.Validator
When we implement this interface we will get the following method:
public void validate(Object event, Errors arg1) {
Event e = (Event) event;
}
Inspired by this thread and never before it I was really concerned of myself doing casts whenever IDE suggests me to. And I have just about few cases when that actually resulted in casting exception and it is never rocket science to understand why it cannot be casted and what should we do about it. Plus we can always comment exactly what object type to expect for other developers to notice.
Just hypothetically if implementation of third party libraries interfaces will always result in Object parameter then what is the fuss in that thread about? Obviously library creators have to use something general like Object to account for our different contexts.
Or maybe I can do it other way in this case?
2. I retrieve something from different context such as database
Hibernate for instance returns me List data structure which is maybe now what I want? I am forbidden to cast from List to ArrayList just because it is not beautiful?
3.session.setAttribute()
; session.getAttribute()
- and then object pass to service method? - no casting how?
By finishing this question I am seriously thinking that "don't do this because it is bad" is either wrong attitude or the component/functionallity from the beginning should not even exist in API.
Upvotes: 0
Views: 80
Reputation: 650
The main problem with casting is that you don't get the compile-time type safety. Where possible we use interfaces (eg. List rather than ArrayList as you mentioned), or inheritance. We also have generic types, eg. List<String>
instead of a list of Object objects.
Sometime it's just not practical to provide specific types in an api without making the api too heavyweight, and we end up having Object references and then cast them because we know the context in which they are being used.
Regarding the List vs ArrayList example... using List here is good. The api provider is just saying that they will return an object which implements the List interface, so you can access it as a list. Your program doesn't want to know the internal implementation of your api provider, and they don't want to give your client any special consideration. By making apis as generic as possible (client specific, but implementation generic) they tend to be as robust as possible.
so "don't do this - it's bad" really means use it as a last resort. If possible, an interface or similar may be a better option.
Upvotes: 1