Archive for the Category Development

 
 

Using <? extends T> and <? super T> for reduce style functions that operate on collections

One of the cases I’ve had to deal with in gwt-pectin is creating Reduce style functions that operate on a collection of values.  The basic idea is to define interface of the form.

public interface Reduce<R,T> {
   R reduce(List<T> source);
}

I use this on my ReducingValueModel<R,T> to automatically compute fields such as a sum’s of numbers, or a string representation of a list and so forth.  So on my ReducingValueModel I have a method to configure the reducing function to use as follows.

public class ReducingValueModel<R,T> {
   // our function
   private Reduce<R,T> function;
   // and it's setter
   public void setFunction(Reduce<R,T> function) {
      this.function = function;
      recompute();
   }
   // and every thing else that makes it go
   ...
}

This works fine when define a new function for each different combination of R and T.  The trouble appears when you want to create a generic Reduce function that you can use on any ReductingValueModel.   Something like a generic “list to string” style function for example:

public class ListToStringFunction<String, Object> {
   // we can convert any list of objects to a string
   public String reduce(List<Object> values) {
     // concate our list values and return the result.
     return ...;
   }
}

So now lets try and use it.

ReducingValueModel<String, Integer> reducingModel = ...;
// This won't compile...
reductingModel.setFunction(new ListToStringFunction());

But this won’t compile because ListToStringFunction is a Reduce<String, Object> and not Reduce<String, Integer>.  So we bung in the standard <? super T> clause on the ReducingValueModel so it can accept a function that works on any super type.

public class ReducingValueModel<R,T> {
  private Reduce<R, ? super T> function;
  // now lets use <? super S> so we can use functions that
  // operate on any super source type.
  public void setFunction(Reduce<R,? super T> function) {
    this.function = function;
    recompute();
  }
}

And while it looks like this should work, it doesn’t.  The problem is that were I’m using the Reduce function it’s now defined as a Reduce<R, ? super T> (making it a Reduce<T,Object> for all intents and purposes) so it can’t accept any old List<T> as an argument.

public class ReducingValueModel<R,T> {

  private Reduce<R, ? super T> function;

  protected void recompute()  {
    ArrayList<T> values = ...;  // prepare the values..
    // now this won't compile because our the function we
    // passed in only works on List<? super T> and not List<T>
    R computedValue = function.compute(values);
    fireValueChangeEvent(computedValue);
  }
}

Fortunately the fix is simple.  We need to update our Reduce<R,T> interface to accept any values that extend T.  I.e.

public interface Reduce<R,T> {
   // this allows our Reduce<R, ? super T> to operate
   // on any list that extends T
   T reduce(List<? extends T> source);
}

Now our ReducingValueModel<R,T> can accept functions that work on any super type of T and our Reduce<R,T> can accept any list whose values that extend T.

So the two things to do are:

  1. Make sure your functions can operate on source collections of type <? extends T>. i.e.
    public interface Reduce<R,T> {
       R reduce(List<? extends T> source)
    }
  2. Allow users to configure functions use <? super S> for the source values.  i.e.
    public void setFunction(Reduce<R, ? super T> function) {...}

All good.

Simplifying

I always find it healthy to come back and use code you wrote a while ago. There’s nothing like a bit of space to help see things in a new light. Often too you can be so focused on solving one problem that you don’t get a chance to step back and see the bigger picture.

And so it was when using my binding framework the other day. Don’t get me wrong, I really like it. But the first pass gave me flexibililty I needed, but not the simplicity I needed for day to day regular use. Who really wants to create presentation models using the following?

// somewhere at startup
Pectin.registerMixin(ComponentMixin.instance());

// then when you need a presentation model
PresentationModel<ComponentValueModel> pm =
      new PresentationModel<ComponentValueModel>();

// and use the "firstName" value model..
pm.get("firstName").setEnabled(false);

What’s a ComponentValueModel anyway and why do I need one? As it turns out I almost always want one (since it gives my value models the common enabled, visible, and editable properties) so why do I have to specify it every time? Then there’s validation, you almost always need that too.

So, short story long, I’ve layered the API. The original classes have been moved to a lower level (i.e. GenericPresentationModel) and I’ve created new implementations that extend them and that come pre-configured with the default interfaces. I’ve also installed the associated Mixins automatically so for everyday use it’s now just:

// This is much better
PresentationModel pm = new PresentationModel();
pm.get("firstName").setEnabled(false);

Much nicer.

Farewell Tapestry and Hello GWT

With the upcoming release of Tapestry 5 I’ve decided to take the plunge and try out GWT. I’ve long been a Tapestry fan (I can’t stand the goto development style of Struts), but this latest version has left me a little wanting. In short:

  • It’s changing dramatically again.
  • The framework now magically invokes methods if they follow particular conventions.
  • I hate method conventions. Intellij IDEA is really good at telling me all kinds of useful things. Method conventions bugger that up completely.
  • Tapestry documentation has always been lacking, this magnifies the previous gripe by a factor of 100.

Once I realised the depth of my grumpiness I decided to re-evaluate the webapp landscape. Since I’m not interested in ruby/rails I decided to give GWT a whirl.

The GWT approach is different. You don’t develop a web application with lots of pages etc, you write Javascript application which you then embed in a given web page (I.e. a bit like embedding an Applet in a page). While it’s not a solution for generating websites, it’s great for developing web applications.

What’s more, you write your Javascript in Java. Sweet. I get everything Java gives me (well a fair bit anyway) like packages, interfaces and type safe refactoring etc.

Some of the good points are:

  • The documentation is great. Well thought out and well written.
  • The shell environment is wonderful. The best out of the box web development experience I’ve had yet.
  • The client aspects of the application are written using standard client techniques. Observable models, reusable widgets, similar development approaches.
  • My server is stateless.

Things that could be better:

  • There’s no binding API. Life without binding sucks. There are apparently plans for one, but in the mean time it took me a week to migrate my Swing binding framework over to GWT.
  • It would be nice if there was an easier way to add servlet context listeners and context parameters to the shell environment.
  • Better documentation on writing compiler plugins would be nice.

Other than that, the combination of GWT in the browser and simple servlets using Guice on the backend has been a delight.

Playing with Google Guice: Look and Feel

In this example I’m showing how I use the LookAndFeelService in conjection with the EnvironmentService to configure the LAF defaults based on the runtime environment. The LookAndFeelModule allows me to configure various look and feel aspects based on the runtime environment.

The LookAndFeelModule is the starting point. You configure it and it configures the LookAndFeelService appropriately.

// create the module
LookAndFeelModule lafModule = new LookAndFeelModule();

// set the default look and feel.
lafModule.setDefaultLookAndFeel(UIManager.getSystemLookAndFeelClassName());

// now configure environment specific lafs
lafModule.registerLookAndFeel(MacOSX.class,
                              QuaquaLookAndFeel.class.getName());

I also use a replacement for JOptionPane that supports application wide and document specific option panes as required by the Mac. This too needs to be configured based on the environment we’re running on.

// Configure the MessagePaneProvider to use by default
lafModule.setDefaultMessagePaneProvider(new GenericMessagePaneProvider());

// now configure environment specific MessagePane providers
lafModule.registerMessagePaneProvider(MacOSX.class,
                                      new MacMessagePaneProvider());

Then I simply pass the module to my application launcher. The application retrieves the LookAndFeelService and invokes its configure method.

Launcher.launch(MyApplication.class, args, lafModule);

Of course instead of repeating this in every application I’ve created a default module implementation that’s preconfigured. So all I need do is:

Launcher.launch(MyApplication.class, args, new DefaultLookAndFeelModule());

And everything just works. Nice.

Playing with Google Guice: Splash Screens

The previous entry showed the creation of a (very) simple single frame application. Splash screens are common, so lets add one. Since there’s no easy way to do it for all occasions, we’ll use a Guice module to provide it for runtimes prior to Java 6.

public static void main(String[] args)
{
   URL splashImage = Main.class.getResource("/images/splash.png");

   // create the splash module for pre Java 6 runtimes.
   Module splashModule = Java5SplashScreenModule(splashImage);
   Launcher.launch(MyApplication.class, args, splashModule);
}

And that’s it. The framework will display the splash screen and all will work fine. Of course if you’re running on Java 6 you’d used the Java 6 version (that uses the new SplashScreen functionality). Of course if we don’t define the service in one of our modules, the framework uses the default `NullSplashScreenService`.

If MyApplicationFrame (or any other class for that matter) wanted to use the splash screen service, it just needs to inject it into it’s constructor.

public class MyApplicationFrame extends JFrame
{
   @Inject
   public MyApplicationFrame(SplashScreenService splashService)
   {
      // do stuff....
      splashService.setImageURL(nextImageURL);
   }
}

Playing with Google Guice

It’s been a long time coming but I’ve finally started dabbling in dependency injection for my swing frameworks. It’s taken me a quite a while to get a feel for where and how it can/should be used. Given the complexity of even an average Swing application I’d been loathed to convert all my UI construction and wiring over to a container, but I’d also love to create a framework environment where I can install all my standard behaviours in one line.

I’d also been wanting to consolidate my various frameworks and utilities into a single application framework (along the lines of JSR-296) but wanted to try out the dependency injection route.

Anyway, so far I’ve been very pleased with the results. I’ve been able to create services for controlling the splash screen, determining the runtime environment and providing runtime environment services, configuring Look and Feel settings and so on. With Guice you can easily create default implementations of your services so you can have the basics going with zero configuration.

So the following useless example shows what’s necessary to get a frame up and create a file in the default application data directory.

public class MyApplication
extends SingleFrameApplication
{
   public MyApplication()
   {
      super("MyApplication", MyApplicationFrame.class);
   }

   public void initialise(String[] args)
   {
      // The EnvironemntService ensures it's the correct location
      // based on the runtime platform.. i.e. `C:\AppData\MyApplication`
      // on windows and `~/Library/Application Support/MyApplication`
      // on the Mac.

      // AbstractApplication provides getters for standard services so
      // you don't have to magically discern their existence.
      EnvironmentService env = getEnvironmentServices();
      File logFile = env.getFileInAppDataDirectory("logs/my-app.log");

      // do stuff with the file...
      ....
   }
}

Then the application can be simply started using the following.

public static void main(String[] args)
{
   Launcher.launch(MyApplication.class, args);
}

Why I generally avoid GUI Builders

How’s that for a non committal title (c:

Most of my own thoughts have been better explained by others.  Beware the GUI Builder is an excellent article on Hacknot, and a response by Karsten Lentzsch to this post sums up the design issues well (search for “Karsten Lentzsch” and you’ll find his comment).

The meta design issues described by Karsten are a major sticking point for me. The implication is that if you use GUI builders and your UI design requires that the label/component gap be 4 DLUs, or that section titles should have 12 DLUs of top padding, then every developer must know every rule and ensure they implement it correctly on every form. You will have problems.

Custom layout builders on the other hand don’t generally suffer the same fate. They’re able to capture the design rules in one place (i.e. the DRY principle) and your developers can live blissfully unaware of the nitty gritty requirements or implementation issues.

For larger projects you can also specialise the builders and integrate them with other infrastructure such as a binding or command framework.

//  a trivial example that doesn't really make sense.
SimpleFormBuilder b = new SimpleFormBuilder();
b.setFormTitle("My Cool Form");
b.addTextField("First _Name", firstNameValueModel);

Of course the real problems with layout builders is that you have to design and write them, and there will always be cases that break the rules. You can minimize this pain however if you start with a decent builder and layer your architecture so developers can drop down to “manual” for the edge cases.

This then is the real issue for me: if you only have a few static screens, then a GUI builder is probably an acceptable option, but once your project grows you’re heading for trouble.

Playing with ANTLR

One aspect that can be annoying when creating value models creating bindings for their enabled and visible states. The following shows a simple example where certain components are enabled and disabled based on the value of others.

Mr Schedule Options

In this screen, the “Use Proxy” is only enabled when “Automatically Check for Updates” is selected, and both the “Host” and “Port” fields are only enabled when both check boxes are selected.

To simplify this kind of operation I’ve been playing around with ANTLR grammars. First off, if you’re like me and have never built a language parser before, just go ahead and buy the book. Building an abstract syntax tree would have been near impossible without it.

So far I’ve been able to get a basic language up and going. The syntax is simple and lets you assign model properties from simple expressions involving other models, for example:

useProxy.enabled = checkForUpdates.value

This binds the enabled property of “useProxy” to the value of “checkForUpdates”. I also let you omit the “.value” for simplicity, so then we get:

useProxy.enabled = checkForUpdates

So state of the all the components in the above image is controlled by the three “bind” lines of code in the PresentationModel.

// install the value models...
installValueModel("checkForUpdates", ..);
installValueModel("useProxy", ..);
installValueModel("proxyHost", ..);
installValueModel("proxyPort", ..);

// and create the bindings
bind("useProxy.enabled = checkForUpdates");
bind("proxyHost.enabled = checkForUpdates && useProxy");
bind("proxyPort.enabled = checkForUpdates && useProxy");

Normally I don’t like putting code in strings, but in this case I think it’s worth it. To limit any possible issues the library barfs during the call to bind if any of the models are missing or don’t define the required properties.

And then there were Mixins

One of the key goals for my binding infrastructure has been to make it easy to extend the value models to suit your business requirements. The idea was let you define a custom value model properties and have the library automatically manage them. I had this working pretty well, but it was pretty painful to set up, and definitely not something I’d wish on others.

Enter Mixins. Somewhere along the line it occurred to me that I could create Mixins that provide standard ValueModel extensions and their handlers out of the box. The first test was to convert my ComponentValueModel interfaces that defines standard component properties such as enabled, editable and visible.

public interface ComponentValueModel extends ValueModel
{
    @DefaultValue(true)
    public boolean isEnabled();
    public void setEnabled(boolean enabled);

    @DefaultValue(true)
    public boolean isEditable();
    public void setEditable(boolean editable);

    @DefaultValue(true)
    public boolean isVisible();
    public void setVisible(boolean visible);
}

Using this mixin is now as simple as..

// install the mixin that defines the ComponentValueModel
// interface and standard handlers.
Pectin.registerMixin(ComponentMixin.instance());

// create a presentation model that vends ComponentValueModels
pm = new BeanPresentationModel<Person, ComponentValueModel>(...);

// all the value models returned by the presentation model will
// implement the mixin interface.
ComponentValueModel cvm = pm.get("firstName");

// changes to the mixin properties will be automatically handled
// by the mixin
cvm.setEnabled(true);
cvm.setEditable(false);
cvm.setVisible(true);

From here the mixin is responsible for updating the state of components bound to ComponentValueModels. The mixin uses styles that map particular model properties to particular components allowing you to control the way particular properties effect particular components.

So far I’m really pleased with the progress.

More Value Model thoughts…

In light of my previous post, I’ve long pondered how I could create a generic PresentationModel/ValueModel framework that can be customised on a per project basis.

  1. Must be able to extend the ValueModel interface with real meta data methods.
  2. Must be able to modify the behaviour of the component bindings to use use the custom ValueModel metadata defined above.
  3. Must support buffering natively.
  4. Must be easy to use out of the box and easy to customise.

I’d had a couple of goes at this in the past but yesterday I had a bit of a moment where I believed it might be possible (either rightly or wrongly).

Ignoring any doubts I tried a few ideas and to my surprise it progressed pretty well. I think this was partly because I’d been spending more time away from the Mac where my brain could think in peace.

Anyway, I shall continue plugging away and see how it turns out.