Tim Jansen's blog


2004/05/15
Generics vs. Autocasting in Eek
Generics vs. Autocasting in Eek Sam Pullara has written a blog entry in which he suggests to use autocasts instead of Java 1.5's generics. It caught my attention because I have a similar decision to make for Eek. I haven't started to specify generics and am not sure about the details yet, so just emitting that feature is an attractive option. What he proposes is to get rid of casts when the value is assigned to a typed local variable (note that this is different from Eek's 'any' type, because 'any' messages are dispatched at runtime and not at compile-time). If Eek would use Java's generics syntax, his Java example would look like this:
Map<String, String> map = HashMap<String, String>()
map.put("key", "value")
String value = map.get("key")
This is the example without generics and autocast ('any()' is Eek's way of upcasting):
Map map = HashMap()
map.put("key", "value")
String value = any(map.get("key"))
And this example shows the syntax with autocasts:
Map map = HashMap()
map.put("key", "value")
String value = map.get("key")
The first two examples both have a redundancy: with generics the type of the Map needs to be specified twice. Without generics and autocasts, the values from the Map need to be up-casted. The second and third example lack compile-time safety for the Map and the code does not specify the allowed types for the Map. I probably hate unspecified types in collections even more than the casts in pre-1.5 Java. If you read code written by others it can be quite difficult to find out the allowed types of a collection. This alone is enough reason for me not to give up generics in favour of auto-casting. I think I have found a third way that is a limited kind of autocasting and makes the syntax more compact, but at the same time keeps the type-safety of generics: just do not require the constructor to specify types, but take the types that are expected in the surrounding expression. With that rule the generics example looks like this:
Map<String, String> map = HashMap()
map.put("key", "value")
String value = map.get("key")
It's shorter, type-safe and documents the allowed types. I think I will take it.


 

This blog is my dumping ground for thoughts and ideas about Eek. Someday Eek will be a programming language and system, somewhat comparable to Java in scope. It is my attempt to bring sanity to the world of computing.
At least I hope so. Right now it is far from being finished and I can't guarantee that it ever will be. I am still working on the specification, but I won't release anything before I got my first prototype running. The world does not need more vapourware and unusable beta-software. All publicly available information about Eek is contained in this blog. You can find the latest summary here.
This page is powered by Blogger. Isn't yours? Creative Commons License
This work is licensed under a Creative Commons License.