Monday, May 18, 2009

Type Safe Classes - 2

In my previous post about Type Safe Classes, we can add two additional public API's



The above two API's look very decent and type safe and there is some hard to find problems here. Lets take this by example; In the below example, we can create a stack of animals and add any Type of animal to the stack. But unfortunately with our published APIs, we can add a Dog to animals [Stack] but cannot add List dogs to same stack using pushAll API, its not allowed (But this is what we want to achive, isn't it.)



Also, there is a similar problem with popAll API as well. Consider the below example, Also we know that its acceptable to collect animal object (any Type) in an Object, but we cannot collect all the animals in List<Object> at once using the above mentioned popAll() API



This wont work either because popAll API only take Collection<E> that means Collection<Animal> in our case. Note that Collection<Animal> is not same as Collection<Object> & similarly Iterable<Animal&tt; is not same as Iterable<Dog>. Question is, if the below code works [we can push any Type of E in the stack]



Below code should have also worked [see below code], for all the Types of E, but it doesn't because thought Animal & Dog has covarient type relationship [the referenced object's type parameter is a subclass], List<Animal> & List<Dog> defines "invariant type relationship", [List<Dog> is not a subtype of List<Animal>]



So, Java 1.5 generics also provide us with wild cards, which is what we have to use here. We have to define a "covarient type relationship" using wild cards.



Our same code which was not working before, will work because we converted our invarient type relationship to covarient type.



One more interesting thing is PECS principle [producer extends, consumer super], what it means is; when we only want to read or use the elements in a collection, we use extends keyword. e.g. pushAll(Iterable<? extends E> elements), we can just read the elements but cannot add anything in elements because the input is producer not a consumer. Even if we had pushAnimal(List<? extends Animal> animals) API, we cannot add any elements, except null, in the collection. So, if we want to add elements in the collection as well, we should use a consumer like popAll(Collection<? super E> collection.

I guess PECS rule is the most tricker of all the rules we have to follow while making our code generic.

Type Safe Classes

We always try to use type safe collections where ever possible, for example

What would it take to implement a type safe Collection like Stack ? Below is the implementation of type safe Stack class


Why I have used "@SuppressWarnings("unchecked")", and still claiming it to be type safe ? First, its type safe for the client using this Stack, its pushes and pops element of type E. Second, we know what we are doing, we are typecasting Object[] to E[]; hence a "@SuppressWarnings("unchecked")."

Friday, May 15, 2009

Groovy & Java

Closure(s) Groovy Closures, loosely speaking are method pointers. Also, Groovy is a 2nd standard language for JVM. So, does it mean we have function pointers in Java / JVM ? No, if you read about Closures carefully enough, they are actually objects. Let’s see if we can do something close to what Groovy can do in Java.

Below is a sample code written in Groovy script


def list = []
for (i in 1..5)
list.add(i);
/*I am treating doThis as a Closure, I could have written 'Closure doThis' as well */
def doSomething(toMe, doThis){
toMe.each(doThis)
}

doSomething(list, {print it + " "})
print("\n")
doSomething(list, {print it * 5 + " "})
print("\n")
list.each{print it + " "}

Below are the results

1 2 3 4 5
5 10 15 20 25
1 2 3 4 5


In the above example, "doThis" can be anything (its loosly typed, feature of dynamic language) but I am using it as a Closure. Method named "doSomething" simply applies the "doThis" closure to "toMe" variable. yea, I know its painful when on one side you say "Following generics, it’s good for you and your code's health" and on the other side "Look @ the really cool features of Groovy, you don’t even need to declare Type".. WTF. Anyways, the point is, what will it take to do the same thing in Java, Groovy style.

Lets first declare something like closure :)


Also, lets implement our own version of List (just to include groovy stype "each" method)



Now, let’s see our code in Action


Below are the results: as expected

1 2 3 4 5
5 10 15 20 25
10 20 30 40 50
1 2 3 4 5


Then only thing interesting in MyGroovy class is below code:


In Groovy list.each() method takes a closure, which is internally just an Object. So, in our implementation of List, we are also passing instance of Closure :). BTW, I do not know how Groovy implements this concept, but this technique is a good candidate. Also, given that SpringSource owns Groovy & Grails, we might see Groovy getting even more popular for web application development. According to me, it is going to be maintenance nightmare if that happens.

Thursday, May 14, 2009

ConcurrentModificationException

While iterating over the List, or anything which implements iteratable, we cannot modify the contents of that particular collection. Not a surprise, but today while implementing iteratable (@ work) I din't know how to achieve this. BTW, why do I need to throw this exception ?? do I care ?? should I not just use object locking ?? I guess all of us know the reason, object state in multithreaded applications & performance. Anyways, I think below implementation looks decent enough: