So I was programming along the other day, tap tap tap enjoying my life as a java programmer. Recently I had attended JAOO in Sydney, and had the pleasure of watching Joshua Bloch of Effective Java fame do his thing. He was chatting about generics, and how as Java people we could possibly get our heads around understanding what was going on.
To assist our little brains, he presented a concept with an acronym he calls PECS.
First, Producer Extends.
If you put things into the object and never retrieve them, the object is a producer. Awesome. Producer extends:
ArrayList<? extends Object> list = new ArrayList<String>();
Secondly, Consumer Super:
If you only retrieve things from the object, the object is a consumer. Consumer super:
ArrayList<? super String> list = new ArrayList<Object>();
So you can imagine why I was so happy programming along in my little lunch box. I was eating this generic candy and it tasted sour, but sour in a way that is cool after you get over the part where you close your eyes and screw up your face. Then this:
ArrayList<ArrayList<? extends Object> list = new ArrayList<ArrayList<String>>();
This is the same example as before, but surrounded in another list. Intuitively I expect this to work, however it doesn’t compile due to “incompatible types”.
Seriously, what the? I don’t understand how this makes any sense. How are we supposed to understand the code that we write if we cant even understand the language? How can we be expected to teach children to learn how to read if they can’t even fit inside the building?
PECS is a useful concept. Unfortunately, Java generics at the moment are limited in their usefulness. They turn simple code into code that is clever and complicated. This slows us down.
Personally, I cant wait till we are all using groovy:
def list = []