Posted on Jul 12, 2008

Class.cast(..) and Generics – a powerful combination

As you know when it comes to casting a la Java 1.4 a developer will have to write, typically, something like this:


Object a = "iron man";
String  b = (String)a;

Well, there is nothing wrong with this code. However, it is not pretty :). With Java 5.0 the casting mechanism is more explicit and nicer. The best thing of it is that it does not throw warnings, which it is a big deal :)


Object a = "iron man";
String  b = String.class.cast(a);

Not that bad, huh? Hmm, well…Okay, Okay, you got me. This still does not look that pretty and it is more verbose than the (Object)a style. How can I make it prettier? the ans: Generics


public static <T, E extends T> E cast(T me, Class<? extends E> to){
    return to.cast(me);
}
....
Object a = "iron man";
String  b = cast(a, String.class); 

Believe it or not, I love this technique. It works like a charm with objects that are part of the same inheritance chain. I know this method requires more tweaking to make it suitable for handling the casting of collections. But hey! this is just a working idea!

Posted on May 14, 2008

Do you need to cache your objects?

I’ve found the Cache Management Pattern very useful in more than a couple of projects that needed a simple caching mechanism. Now that we have Generics at our disposal, I think this pattern deserves a tiny change. Something like a generic structure or code that we can follow or use every time we need to cache specific objects.

The Structure


public interface ObjectCacheManager<K, T> {
    T fetch(K aKey);
}

public interface ObjectFactory<K, T> {
    T make(K aKey);
}

public interface Cache<K, T> {
    void add(T anEntry);
    T fetch(K aKey);
}

An Example

Note: this is just a toy example… you’ve been warned :) Its purpose is to show you the dynamics of this pattern.


public class FooCache implements Cache<String, Foo> {
    private final Map<String, Foo> cache;
    public FooCache(){
        cache = new ConcurrentHashMap<String, Foo>();
    }

    public void add(Foo entry) {
        final String key = entry.getName();
        if(cache.get(key) == null){
            cache.put(key, entry);
        }
    }

    public Foo fetch(String givenAKey) {
       return cache.get(givenAKey);
    }
}

public class FooFactory implements ObjectFactory<String, Foo> {
    public Foo make(String aKey) {
        return new Foo(aKey);
    }
}

public class FooCacheManager implements ObjectCacheManager<String, Foo> {
    private final ObjectFactory<String, Foo>    server;
    private final Cache<String, Foo>            cache;
    public FooCacheManager(){
        server  = new FooFactory();
        cache   = new FooCache();
    }

    public Foo fetch(String aKey) {
        Foo foo = cache.fetch(aKey);
        if(null == foo){
            foo = server.make(aKey);
            if(null != foo){
                cache.add(foo);
            }
        }
        return foo;
    }
}

Let’s get more specific with its use.. shall we?


    @Test
    public void verifyFooCachingSystem(){
        final FooCacheManager manager = new FooCacheManager();
        final Foo a = manager.fetch("Superman");
        final Foo b = manager.fetch("Superman");
        Assert.assertEquals(a, b);
    }

And there you go…

Posted on May 4, 2008

No more downcasting via “Recursive Bounds”

I recently coded a fairly tiny application that made use of the MVC pattern. One of the things that I noticed while I was writing it was that I was down-casting a lot. Imagine something like this:

Example


// main type
interface Model {
	void someMethod();
}

// implementation
class Mixer implements Model {
    public void anotherMethod(){
    	System.out.println("hey");
	}
    public void someMethod() {
    	System.out.println("dude");
	}
}

Now If I want to invoke both methods, I’d have to do something like this:


    final Model m = new Mixer();
    m.someMethod();
    // downcasting .
    // imagine this with more model objects
    // with unique methods...
    ((Mixer)m).anotherMethod();

I am really annoyed about this whole downcasting. It does not make my code look that pretty. So I decided to use Generics; more in specific the recursive bounds idiom which was used in the implementation of the Java 5.0′s Enums.

The solution


interface SuperClass<S extends SuperClass<S>> {
    S subclassInstance();
}

interface AnotherType {
    void print();
}

The next step is to implement the previous interfaces. Something like this:


/**
 * subclass A
 */
static
class SubClassA implements
        SuperClass<SubClassA>,
        AnotherType
{
    private final String name;
    SubClassA(){
        final Random random = new Random(19580427);
        name = getClass().getName()
                + random.nextInt();
    }
    public SubClassA subclassInstance(){
    	return this;
	}
    public void print(){
    	System.out.println(name);
	}
}

/**
 * subclass B
 */
static class SubClassB implements SuperClass<SubClassB>,
        AnotherType
{
    private final String name;
    SubClassB(){
        final Random random = new Random(19580427);
        name = getClass().getName()
                + random.nextInt();
    }
    public SubClassB subclassInstance(){
    	return this;
	}
    public void print(){
    	System.out.println(name);
	}
}

Then I can write code like this one and totally avoid dowcasting between objects:


public static void main(String... args){
 final SubClassA      		 sca  = new SubClassA();
 final SuperClass<SubClassA> sc   = sca;
 final SubClassA      sca2    = sca.subclassInstance();
 final SubClassA      sca3    = sc.subclassInstance();

 // no casting..cool huh!
 sca2.print();
 sca3.print();
}

And there you go… I’ve totally solved my downcasting problem!