This post originated from an RSS feed registered with Agile Buzz
by James Robertson.
Original Post: Comments on static/dynamic
Feed Title: Cincom Smalltalk Blog - Smalltalk with Rants
Feed URL: http://www.cincomsmalltalk.com/rssBlog/rssBlogView.xml
Feed Description: James Robertson comments on Cincom Smalltalk, the Smalltalk development community, and IT trends and issues in general.
What's the real reason I get ClassCastExceptions? Because I refactor a lot. After a refactoring the wrapper class to use B instead of A you might be putting a type B into the collection and incorrectly casting it to the old A in a wrapper class method
.
This problem will go away when generics are introduced and I can specify the type I want a collection to contain. The compiler will tell me I'm trying to put a B into collection<A> and I'll be forced to refactor it to collection<B>. Then the compiler will tell me I'm casting an item from collection<B> to an A (the place where the ClassCastException formerly occurred for me). Actually Eclipse will tell me these things as I type, instead of at compile time.
As I understand it, and I could be way wrong as usual, languages like Smalltalk don't have this problem because they don't enforce type, so you never cast an object coming out of a collection (I assume there is a complementary group of classes to Java Collections in Smalltalk). If I were refactoring the same problem in Smalltalk, without the ClassCastException I may never know that I'm returning an object of the wrong type after the refactor (A instead of B). To catch this problem, you'll need good unit tests and you'll need to change them all from using A to B. You could always just nuke the A class, and the compiler will tell you it's invalid. With static typing in Java and generics, you don't have to nuke A.
You don't have this problem in Smalltalk because it's not the sort of problem you tend to get yourself into, period. Say I had a collection holding Foos. If I refactor, and I end up having a collection holding Bars (completely incompatible), then I have bigger problems. Even so, I would have had to refactor all the surrounding code that accesses the collection elements - and if I didn't have tests under those circumstances, I'm in trouble whether I have static typing or dynamic typing. To be brutal, if you trust the compiler to solve this for you, then you shouldn't be writing code.
Far more common is the case where I have a collection of objects that conform to a specific API (without regard to their class membership) - and I need to add a new sort of object that also conforms to the API. or I need to extend the API. This is simple, and I do this sort of thing all the time. Still - you have to test this. If you trust the compiler to solve this, you aren't going to end up being happy either way...