Dull points about GWT Java SE 6.0 Release 1 Preview
Jul 31

It seems that in almost every system I write has a bi-directional containment. For example, a Table instance containing Column instances that should know to reference back to the Table instance containing them. Sometimes, when writing an API that uses these kind of tables and columns and allows the user of the API to define them, type safety using Generics is wanted.


Let’s look at the non-Generic case first:


public interface Table {
  Collection getColumns();
}

public interface Column {
  Table getTable();
}

However, as said in the beginning of the post, we want Table to know which specific Column it is containing. So, we’ll define Table as Table<TColumn>:


public interface Table<TColumn extends Column<TColumn>> {
  Collection<TColumn> getColumns();
}

public interface Column<TColumn extends Column<TColumn>> {
  Table<TColumn> getTable();
}

A type parameter was added to Table. However, that type is needed in Column as well to describe the Table containing it, so it was added to Column too. The idea of the weird circular typing is explained in another post of mine.

As this is fixing the problem of Table knowing exactly which type of Column it’s containing, it doesn’t solve the issue of the Column wanting to know exactly which type of Table contains it. Since we want Column.getTable to return TTable, we’ll have to change the code to the following:


public interface Table<
  TColumn extends Column<TColumn, TTable>,
  TTable extends Table<TColumn, TTable>> {
  Collection<TColumn> getColumns();
}

public interface Column<
  TColumn extends Column<TColumn, TTable>,
  TTable extends Table<TColumn, TTable>> {
  TTable getTable();
}

So now, if I had a MyTable instance it would be forced to return a collection of MyColumn instances, and they in turn would be forced to return a MyTable instance back. The sad part that because of type erasure it will all compile to the first code segment. However, type-safety will retain itself in compile time, and that’s what’s important to most of us (I gather).

Other posts of interest

Leave a Reply

Chaotic Java is Digg proof thanks to caching by WP Super Cache!