Sunday 7 October 2007

Generics/template: giving peace of mind to the anal-retentive

I admit it: I am obsessive. So I am a bit conflicted about Object Oriented Programming. To be true to the concept, objects themselves should define whether they accept a message or not; type checking should not be allowed, since it should be impossible to realize beforehand whether a message (a function call in other paradigms) is valid or not until it is passed to the object. However, not adhering to theory has lots of advantages. On one hand, static typing allows you to detect errors at compilation time, errors that wouldn't be detected until the function is executed; that is certainly a huge advantage, especially since not many people are comfortable with mutable code. In addition, if a call is not polymorphic, it has better performance (this advantage is quite minor, since the performance improvement is very minor).
Java and C++ were strong typed, and life was easy and nice to your average control freak. However, there was a thing in Java (up to 5.0) that bothered me a a bit. You could only add “Object”'s and get “Object”'s from Collections, so to get syntactic errors if you added the wrong type to a collection you had to either to do a very strange casting when adding to the collection (every time casting to the desired class and then letting the implicit casting to “Object” work, without forgetting once about the casting) or you had to subclass the desired Collection instance (which was safer, but you made a bigger mess by adding unnecessary classes). Fortunately, by using Generics (or templates in C++) you can don't have to do anything for type checking the input, you can specify what objects should be contained in a Collection when you must pass a parameter and you don't have to cast the get function, all through a simple syntactic trick (unfortunately, not everything is just a syntactic trick away)

Add to Technorati Favorites

No comments: