Archive for the ‘Uncategorized’ Category

Self-bounding Visitor

Tuesday, January 5th, 2010

I came across the generics self-bounding pattern, thanks to Olivier’s blog [in french] that uses it to describe fluent extensible interfaces. After a bit of research I found a very interesting forum thread that was talking about that pattern more in depth, in particular how it is possible to extend the pattern to a couple of classes.

Let’s just start with a simple example, a binary tree class:

abstract class Node<E extends Node<E>> {
   public E left;
   public E right;
}

class FooNode extends Node<FooNode> {
}

class BarNode extends FooNode {
}

class JuuNode extends Node<JuuNode> {
}

With that design, we constraint the Node class to be subclasses and have its children to be a subclass of its own subclass, and now we can write:

FooNode root = new FooNode();
root.left = new FooNode();
root.right = new BarNode();

But that is not possible:

FooNode root = new FooNode();
root.left = new JuuNode();

If you have carefully read the forum thread, someone posted an interesting extension of the pattern that uses two classes.

The Reflext framework I started to write a few months ago was using a visitor pattern to visit a set of types. There are several ways to visit a set of types, one of them is to visit the class hierarchy of super classes and implemented interfaces. There are many ways to implement the visitor pattern, one of them relies on decoupling the visitor from the code (or strategy) that takes care of doing the visit. The main interest is to reuse the visiting strategy many times and avoid the visitor to care about how visit is done, the visitor only cares about the overall strategy.

Based on this assumption, we can define two interfaces named Visitor and VisitorStrategy that will vary together, as it makes sense to use a hierarchy visitor with the hierarchy visitor strategy. Let’s start with the base interfaces. We use it a Type object as visited object, in the reflext framework it’s a TypeInfo interface that represents a type (which can be either runtime reflection or APT compile time reflection).

interface Visitor<V extends Visitor<V,S>, S extends Strategy<V,S>> {
  // The interface is empty as the base visitor does not provide an API
}
interface Strategy<V extends Visitor<V,S>, S extends Strategy<V,S>> {
  void visit(Type type, V visitor);
}

Now we can define the hierarchy visitor and its strategy

interface HierarchyVisitor<T extends HierarchyVisitor<T>> extends
  Visitor<T, HierarchyStrategy<T>> {

  // The API for hierarchy visit
  void enter(Type type);
  void leave(Type type);
}

abstract class HierarchyStrategy<T extends HierarchyVisitor<T>> extends
  Strategy<T, HierarchyStrategy<T>> {
  public void visit(Type type, T visitor) {

    // We only accept type which are java classes
    if (type instanceof Class) {
      if (accept(type)) {

        // Visitor callback
        enter(type);

        // Now visit the super class if we have one
        Class clazz = (Class)type;
        Class superClazz = clazz.getSuperClass();
        if (superClazz != null) {
          visit(superClazz, visitor);
        }

        // And now visit the interfaces
        for (Class itf : clazz.getInterfaces()) {
          visit(itf);
        }

        // Visitor callback
        leave(type);
      }
    }
  }
  abstract boolean accept(Type type);
}

We can see that the hierarchy visitor and its strategy vary together because they are constrained by design. The last piece missing is the to make vary the strategy (otherwise we would make the visitor and its strategy the same class…). We do it via an enum that provides several strategies

enum HierarchyScope {
  ALL() {
    public <T extends HierarchyVisitor<T>> HierarchyStrategy<T> get() {
      return new HierarchyStrategy<T>() {
        public boolean accept(Type type) {
          return true;
        }
      }
    }
  },

  ANCESTORS() {
    public <T extends HierarchyVisitor<T>> HierarchyStrategy<T> get() {
      return new VisitorStrategy<T>() {
        public boolean accept(Type type) {
          return (type instanceof Class) && !((Class)type).isInterface());
        }
      }
    }
  };

  public abstract <T extends HierarchyVisitor<T>> HierarchyStrategy<T> get();

}

Et voilà, now we can use safely the visitor. I’m not convinced that is a great piece of software, I’m just sure that it was very fun to write and research. Without the mentioned blogs and my favorite IDE (Intellij IDEA) it would have been nearly impossible to write correctly :-).

Self-bounding generics is a curious beast, it’s even called there “That Recursive Java Generics Thing”. Have fun!

Type Safe Enumeration with Java Generics

Tuesday, July 28th, 2009

I’ve been working with Java 5 Generics for about one year now and one pattern that emerged from my experience is the use of generics to create enumerations that provide type safety (I don’t claim to be the inventor of that pattern, actually I don’t even claim it is a pattern).

Often type safety can be achieved by using method type variables like

public abstract <N extends Number> createNumber(Class<? extends N> numberType, String stringValue);

The drawback of this solution is that all the classes must belong to the same hierarchy, in that example they all need to be a subclass of java.lang.Number. The most direct workaround is to free the type variable from its upper bound java.lang.Number. That makes the choice very large since any subclass of java.lang.Object can be accepted.

It is also impossible to prevent some subclass to be used as type argument at compilation time. Failure would have to happen at runtime with an java.lang.IllegalArgumentException thrown for instance.

Those two limitations makes the method not easy to understand the first time you see it, specially when it is part of an API, and it is not possible to make it type safe (actually not as far as I know :-) ) as Java Enums cannot be used as a generic declaration.

So I had to find a way to express an enumerated type that would be type safe. The solution I found is actually not an enumeration in the old/classic way we use to know it before Java 5 Enums (i.e it is class that has a private constructor with public static fields) and therefore it cannot be used in a switch statement. That probably is the only drawback I found but it is a more acceptable issue than the two problems I had before.

Let’s assume we represent a concept of simple types which are arbitrarily defined by String, Boolean and Integer with

public class SimpleType<S> {

   public static final SimpleType<String> STRING =
      new SimpleType<String>(String.class);

   public static final SimpleType<Integer> INTEGER =
      new SimpleType<Integer>(Integer.class);

   public static final SimpleType<Boolean> BOOLEAN =
      new SimpleType<Boolean>(Boolean.class);

   private final Class<S> javaType;

   private SimpleType(Class<S> javaType) {
      this.javaType = javaType;
   }
}

Now we can easily use it as a type safe enumeration, for instance here is how I would write a parse method:

/*
 * Note : yeah this is not really OO and it could be
 * possible to have an abstract parse(String s)
 * method on the SimpleType class and have the static
 * method delegate to it. I leave it as an exercise
 * for the reader.
 */
public <T> T parse(SimpleType<T> simpleType, String s) throws NullPointerException {
   if (simpleType == null)
      throw new NullPointerException("No null simple type is accepted!");
   if (s == null)
      throw new NullPointerException("No null string can be parsed!");
   if (simpleType == SimpleType.STRING)
      return s;
   if (simpleType == SimpleType.INTEGER)
      return Integer.valueOf(s);
   if (simpleType == SimpleType.BOOLEAN)
      return Boolean.valueOf(s);
   throw new AssertionError("impossible!);
}

This way we enforce the set of types that can be passed as arguments in our method and we do it in a manner that will enforce the developer to write type safe code.

Next time I’ll show you have it is possible to improve the pattern efficiency and usability by adding methods on the Type Safe Enumeration class.

The future is so bright…

Friday, September 5th, 2008

…that I almost need my shades.

eXo Platform SAS announced officially today that I am now part of the eXo Platform crew as Portal Product Manager.

JSON support for WordPress

Thursday, August 14th, 2008

I find quite strange that nobody ever provided support for that. Googling about JSON support for WordPress did not return anything relevant. At all.

I use the JSON support in my home page. It is used to display the last 5 blog entries of this blog in the side bar. It does not appear at first as I did not want to clutter the page, so you need to hover the mouse over the blog section and you will see it appear using a nice fading (thanks to jquery).

Anyway here is the php code for WordPress. It is not a plugin because it does not interract with the heart of the system and WordPress does not seem to have an architecture for adding that kind of feature. I believe it should rather be a core feature of the product rather than an extension.

First step, create a file called wp-json.php at the root of WordPress:

<?php
if (empty($wp)) {
	require_once('./wp-load.php');
	wp('feed=json');
}

require (ABSPATH . WPINC . '/feed-json.php');

?>

Then create a file named feed-json.php in the wp-includes folder:

<?php
header('Content-Type: application/json; charset=' . get_option('blog_charset'), true);
$more = 1;

$items = array();
query_posts("");
while (have_posts()) :
the_post();
$item = array(
	"title" => get_the_title_rss(),
	"link" => apply_filters('the_permalink_rss', get_permalink()),
	"description" => apply_filters('the_excerpt_rss', get_the_excerpt()));
$items[] = $item;
endwhile;

$arr = array(
'title' => get_bloginfo_rss('name'),
'link' => get_bloginfo_rss('url'),
'description' => get_bloginfo_rss('description'),
'language' => get_option('rss_language'),
'item' => $items);

echo "".$HTTP_GET_VARS["callback"]."(".json_encode($arr).");";
?>

Then the URL to use it is http://yourdomain/yourpath/wp-json.php?callback=myfunction. The callback is mandatory (if you don’t want it, modify the php script above) in order to make the feed mashable directly in a web page. It will return data like:

myfunction({"title":"It is what it is","link":"http:\/\/blog.julienviet.com","description":"A pure technical trip","language":"en", ..... });

I’ll explain later in another post how I consume it in my home page.

Syntax highlight support

Thursday, August 14th, 2008

I’ve just added support for the syntax highlight using the very good project SyntaxHighlighter.

I used the WordPress plugin Google Syntax Highlighter for WordPress but not without pain.

Indeed there is a CSS conflict between SyntaxHighlighter and Wordpress at the list level that makes the highlighted code to be displayed with additional margins. If you want to see what I mean, download the plugin for WordPress and look at the screenshot. The plugin on my blog is fixed.

So now the fix: modify the file Styles/SyntaxHighlighter.css in the plugin (which originally comes from the SyntaxHighlighter project). Add the following at the bottom:

html > body .entry div.dp-highlighter li
{
	margin:0px 0pt 0px 0px;
}

Syntax highligher test

Wednesday, August 13th, 2008

Testing syntax highlighter plugin

public class Hello
{
   public static main(String[] args)
   {
      System.out.println("Hello");
   }
}
function hello()
{
   alert('hello');
}

Unofficial launch

Wednesday, August 13th, 2008

This is the unofficial launch of my blog.

My home page went alive a few days ago and after that I’ve managed to install wordpress and customize it for my needs. Well almost, I still need to add the syntax highlighter plugin and do a couple of other things.

Working on my home page and the blog was a rich experience, actually I never really managed to do so called client side mashups and now I understand better what it is about. Thanks to javascript and JSON, I’ve been able to integrate Twitter and my blog feed into my home page without requiring any server side code. I did it that way for the sake of simplicity in term of development, as I’ve been able to work directly on the page without the need of any server. There’s a trade off though, doing that kind of mashup is not an easy task and requires considerable skills.

I still have a few things to tune in order to officially launch the blog/site and drink Champagne. For instance I may consider to change the default theme of the blog although it is quite nice, it obviously has a taste of déjà vu. Actually I am considering to pay someone to create a custom theme, but I would need to find the right person first.

I hope to open next Monday, see you next week!