Posted on May 28, 2008

Documenting Exceptions via Factory Methods

Jesse described a technique for handling methods that always throws. This is a very interesting technique. Having written that, would it not be nice to encourage the use of this technique, in our Java coding conventions, as a way to document DRY exceptions? Honestly, I’d’ think we should. It would prevent us from repeating the same description of our exceptions numerous times in our JavaDocs… Disclaimer: this is just a very simple example that tries to convey my point :)


/**
 * @throws Violation
 *      due to {@link #unableToFindConfigFile(String, Throwable)}
 */
public void loadConfig() throws
Violation {
  try {
     //.... some code goes here to
     //.... load a config file.
  } catch (RuntimeException re){
	throw unableToFindConfigFile(
           "loadConfig():void",
           re
        );
  }
}

/**
 * @throws Violation
 *      due to {@link #unableToFindConfigFile(String, Throwable)}
 */
public void refreshConfig() throws
Violation {
	loadConfig();
}

private static Violation unableToFindConfigFile(
	String pointOfCall,
	Throwable cause
) throws Violation
{
	final StringBuilder msg = new StringBuilder()
		.append("Error when calling ")
		.append(pointOfCall)
		.append(". Reason:")
		.append(cause);
	throw new Violation(msg.toString(), cause);
}

/**
 * @throws Violation
 *   due to {@link #unableToFindConfigFile(String, Throwable)}
 */
public void loadConfig() throws
Violation {
   try {
	//.... some code goes here to load
	//.... a config file.
    } catch (RuntimeException re){
	throw unableToFindConfigFile(
		"loadConfig():void",
		re
	);
    }
}

/**
 * @throws Violation
 *   due to {@link #unableToFindConfigFile(String, Throwable)}
 */
public void refreshConfig() throws
Violation {
	loadConfig();
}

private static Violation unableToFindConfigFile(
	String pointOfCall,
	Throwable cause
) throws Violation
{
	final StringBuilder msg = new StringBuilder()
		.append("Error when calling ")
		.append(pointOfCall)
		.append(". Reason:")
		.append(cause);
	throw new Violation(msg.toString(), cause);
}

Some of this approach’s benefits:

  1. No more boilerplate text when documenting exceptions.
  2. The intent of the exception is clearly communicated via a factory method.
  3. We are hiding the complexity of the exception’s declaration behind a consistent exterior.

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 13, 2008

DRY benchmarking….

Every time we try to write a benchmark for particular functionality, we habitually specify a load (max iterations), write a for-loop, set timers before and after the loop, and call the method of interest inside this loop. This typically involves copying & pasting from another benchmark and adapting the current benchmark to your needs. Why don’t we try, instead of copy & paste, to define an idiom that we could reuse for writin benchmarks? Something like this


public class Benchmark {
    private final int iters;
    public Benchmark(int iters){
        this.iters = iters;
    }

    public <T>long given(
    final Callable<? extends T> op
    ) throws Exception
    {
    	// warm things up
        for(int idx = 0; idx < 10000; idx++){}

        long time = System.nanoTime();
        for(int idx = 0; idx < iters; idx++){
            op.call();
        }
        time = System.nanoTime() - time;
        return TimeUnit.NANOSECONDS.toMillis(time);
    }
}

How can use this? This is simple….


    public static void main(
    String[] args
    ) throws Exception
    {
      System.out.println(new Benchmark(100000).given(
      	new Callable<Void>(){
            public Void call() throws Exception {
                System.out.println();
                return null;
            }
      }));
    }

Using this idiom will make the benchmarking of method calls easier…So please start using it :)

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!

Posted on May 3, 2008

A pattern for using EasyMock…

Ralf Stuckert wrote a great article on EasyMock titled "Getting started with EasyMock2."  He clearly defined a pattern for using this library.

The pattern is

    1. Create a mock.

    2. Set up your expectations.

    3. Set the mock to replay mode.

    4. Call your code under test.

    5. Verify that your expectations have been met.

Believe me, knowing this pattern will save you a lot of time trying to figure out how to really use EasyMock when writing tests.