A life committed to learning.

Expressive programming in Java

In Ruby On Rails, for example, you can use a construct like this:

raise ActiveRecord::RecordNotFound unless condition

It’s simple to understand and easier to use, though you can also use the more classical format

if !condition
    raise ActiveRecord::RecordNotFound
end

Because of that I like also to use this kind of expressiveness in Java. Instead of thinking like:

if this then do that

I like to think like:

do that if this

Of course, is a matter of felling well while programming 🙂

Let’s take an example in Java. In this example there’s a simple API to put something in a cache and you will use a “key” to identify your objects in the cache. But because I, as API designer, don’t want you to use the string “key” as key, I will code the cache like this:

package eu.jpereira.exprogramming.cache;
public class MyCache {

  public static void addToCache(String key, Object object) throws Exception {
    if ( key.equals("key") ) {
      throw new Exception("Hey dude, key cannot be 'key'!!");
    }
    //do that cache thing
    System.out.println("Cool! You've added it to the cache!!");
  }	
}

But I prefer doing something like this:

package eu.jpereira.exprogramming.cache;
import static eu.jpereira.exprogramming.cache.ExceptionRaiser.*;

public class MyCache {

  public static void addToCache(String key, Object object) throws Exception {
    throwIfTrue(new Exception("Hey dude, key cannot be 'key'!!"),key.equals("key"),);
    //do that cache thing
    System.out.println("Cool! You've added it to the cache!!");
  }	
}

And the throwIfTrue method is coded like this:

package eu.jpereira.exprogramming.cache;

public class ExceptionRaiser {

  public static <T extends Throwable> void throwIfTrue(T exception, boolean condition) throws T {
    if (condition) {
      throw exception;
    }
  }
}

Even If at the first sight it may seems to be a lot of more work, it’ll pay off with my amusement while programming 🙂 Moreover, it’s easier to understand and to program like this.


jpereira

http://jpereira.eu

View more posts from this author

Leave a Reply

Your email address will not be published. Required fields are marked *