Monday, January 30, 2006

SWT/JFace integer flags and constructors

SWT/JFace is pretty cool. But one thing I will never understand is why the heck are the flags in the constructor of widgets integers. Let's take TableViewer as example: TableViewer(Composite parent, int style). When you want to set style parameter, code completion does not help. So you have to read the (3.1) javadoc of TableViewer it says: @param style SWT style bits. Great, but not very helpful. Ok if you are clever, you know that TableViewer passes the status flags directly to the Table constructor. The documentatios there there indicates that the following flags can be used SWT.SINGLE, SWT.MULTI, SWT.CHECK, SWT.FULL_SELECTION, SWT.HIDE_SELECTION, SWT.VIRTUAL
Ok this gives you a hint, what to use. But if you follow the link to SWT.MULTI, you read: "Used by Text,List and FileDialog"... Hmm, no mentioning of Table....

I don't want to blame the documentation. The problem comes from the design choice to use integer bits constants in the first place. If you look into the class SWT, you are simply overwhelmed by all the integer constants. I see two solutions (in Java 1.4): >
  1. eclipse supports structured comments for code completion, and the javadoc would reflect the flags correctly.
  2. Use some classes representing the flags:
If Table would have a public static inner class like this:

public static class Style {
int flags;
public Style(){}
protected Style(int flags) {
this.flags=flags;
}
public Style multi() {
return new Style(flags|SWT.MULTI);
}
public Style full_selection() {
return new Style(flags|SWT.FULL_SELECTION);
}
...
}
Then the constructor of TableViewer and Table would take this class. You would have all the benefits of code completion and documentation. Internally, SWT could still use integer bit flags, but as a user I would have a fully typed constructor: Instead of new TableViewer(parent,SWT.MULTI|SWT.FULL_SELECTION) I would use the fully typed construct new TableViewer(parent,new Table.Style().multi().full_selection()). Code completion would help me. No more wrong flags! I would love to see additional constructors(and methods) with typed versions....