preload
Jul 09

I’ve jumped ahead in the book. The next few sections cover a variety of different components where we could use the same sort of tricks with closures and extension methods to make the interactions a little nicer but I don’t think there’d be much value to that. I’ve skipped ahead to page 93 where we encounter forms for the first time.

Forms are interesting because they introduce bean-bindng - automatically associating form fields with properties of Java objects.

I’m a little surprised to find this in here, on one hand it feels like a step towards the ‘Naked Objects’ approach which I really like but on the other hand, I’m not sure why the Form abstraction is needed in a framework that has such powerful Ajax functionality. I have my suspicions that this is a holdover from an earlier time, a time when Vaadin was more request/response oriented. It is interesting nonetheless, and I’ll see where it leads me.

I am expecting to run into some problems here. Scala code doesn’t always look the way I’d naively hope from the Java side of the fence.

So, here we go. Version 1. Imagine we were building a Pirate administration tool…

package spike

import com.vaadin.Application
import com.vaadin.data.util.BeanItem
import com.vaadin.ui._

class Pirate {
    private var name: String = ""
    private var weight: Int = 0

    def getName: String = {
        return name
    }

    def setName(newName: String): Unit = {
        this.name = newName
    }

    def getWeight: Int = {
        return weight
    }

    def setWeight(newWeight: Int): Unit = {
        this.weight = newWeight
    }
}

class SpikeApplication3 extends Application {
    override def init: Unit = {
        val mainWindow = new Window("And now... a form.")

        val form = new Form()
        form.setCaption("This be the caption. Yes it be, it do!")
        form.setDescription("What we 'ave 'ere is a tool fur the displayin' o' pirates.")

        form.setItemDataSource(new BeanItem(new Pirate))

        form.setValidationVisible(true)

        mainWindow.addComponent(form)
        setMainWindow(mainWindow)
    }
}

That works pretty well. I defined a Pirate class and adhered to the gnarly Java syntax for defining Bean properties and, hey presto, we have a form with two bean properties nicely represented on it.

The property syntax is just plain fugly though. Let’s get to the Scala pimp action.

package spike

import com.vaadin.Application
import com.vaadin.data.util.BeanItem
import com.vaadin.ui._
import reflect.BeanProperty

class Pirate {
    @BeanProperty var name: String = ""
    @BeanProperty var weight: Int = 0
}

class SpikeApplication3 extends Application {
    override def init: Unit = {
        val mainWindow = new Window("And now... a form.")

        val form = new Form()
        form.setCaption("This be the caption. Yes it be, it do!")
        form.setDescription("What we 'ave 'ere is a tool fur the displayin' o' pirates.")

        form.setItemDataSource(new BeanItem(new Pirate))

        form.setValidationVisible(true)

        mainWindow.addComponent(form)
        setMainWindow(mainWindow)
    }
}

That’s much better. We’ve replaced the fuglyness with an annotation. This annotation is interesting. From a Scala perspective, it doesn’t really do anything. From a Java perspective there’s a world of difference. The annotation tells the scala compiler that the output should include Bean style getters and setters for the this property. In effect the annotation provokes the compiler into doing a chunk more work so that we don’t have to.

I’m not happy though. I always hated the Java convention whereby beans should have no-arg constructors. The number of bugs that I’ve seen stemming from improperly initialised objects is, well, it’s too damn many.

class Pirate(@BeanProperty var name: String, @BeanProperty var weight: Int)

There’s our Bean class, replete with two arg constructor. I like it.

Another experiment. Scala’s BeanDisplayName should be able to be used to change the label placed on the field - assuming the Vadiin developers have gone through the BeanInfo for the class rather than using simple reflection to guess at properties.

class Pirate(@BeanProperty var name: String, @BeanProperty var weight: Int) {
    @BeanProperty @BeanDisplayName("Landlubbers put to the sword") var victims: Long = 0
}

Sadly this doesn’t work. The field that appears in the form is labelled Victims rather than ‘Landlubbers put to the sword’. Whether this is a hole in Vaadin, a problem with Scala, a problem with the Scala to Java integration or just because I screwed up I can’t say.

Jul 05

In part 4 of the Scala & Vaadin series I threw in the line “I believe that comments are, for the most part, an abomination” without really explaining it.

There are a couple of comments on that post that I think explain my position - and other people’s reaction - in more detail.

Jul 03

The next few examples in the book cover adding event handlers in more detail. I think we’ve beaten the ‘closures are definitely the best way to do this’ horse until it’d like us to stop so… I’ll move farther on.

When we get to Chapter 5 we come across an interesting section on resizing components. All components implement the Sizeable interface. The sizeable interface has methods for setting the height and width of the component. There are two choices for each of these methods - set the value as a float along with a unit of measurement, or set the value using a String with the value and the unit.

component.setWidth(12.5, Sizeable.UNITS_EM);
component.setHeight("23%");

I don’t find either of these choices to be that inspiring. Not bad, each is just a little sub-optimal, for my particular sensibilities. I’d rather type something that looks like

component.setWidth(7 pixels)

It is a small change, but one that I think makes the code look a little bit clearer, a little bit more expressive. So how do we make it work? Implicit conversions to the rescue. So what’s an implicit conversion? In short, by explicitly importing an implicit conversion into a scope, you give the compiler the ability to transform one specific type into another specific type if it needs to. That’s a hard sentence to understand, and it probably isn’t even correct ( any Scala boffins that want to correct me, feel free ). In practice it is easier to understand. Here’s the code that I’ve added to VaadinUtils.scala:

class Dimension(private val value: Number) {
    def pixels : String = value + "px"

    def percent : String = value + "%"
}

object Dimension {
    implicit def intToDimension(value: Int): Dimension = new Dimension(value)    

    implicit def doubleToDimension(value: Double): Dimension = new Dimension(value)
}

And then in the imports at the top of my class I import Dimension._ and, presto, I can now use 21 pixels or 34.5 percent ( or 21.pixels or 21.pixels() ) in my code.

What’s really going on? Well, as I understand it, when Scala sees an int with a pixels() method being called on it, it scouts around for an implicit conversion that it could apply that would make the code compile. Now, I’m sure that this sounds scary and dangerous, that’s why Scala is very conservative about conversions.

You’ll notice that I’ve had to define an implicit conversion for both Int and Double because Scala won’t even perform that conversion automatically. One of the things I like about Scala is that it gives you power whilst trying to minimise risk. Neat.

Jul 02

Kent Beck asked some interesting questions around the behaviour of the software community with respect to ‘getting paid’.

I’ve been irked by the behaviour of the community on this subject for quite a while. Personally I blame paranoid ass-hats like this. Harsh but…

Jul 01

Firstly, I’d like to thank all the people who’ve said nice things about the first three parts - here, on twitter and on various news-groups. Of special note is Mark Harrah, the creator of SBT. Not only did he drop me a nice note, he made a change to SBT so that the issue whereby you couldn’t usefully run jetty in batch mode is solved. Now that’s service!

I’d also like to apologise to the people who’ve been reading my blog on the web. I realise that I need to change to a variable width column layout so that you can actually see all of the code. I’ll get to it soon… honest.

Last time I promised I’d talk about continuous compilation and deployment. This is pretty complex, so try to keep up.

Normally to compile all the code and run jetty you’d type:

~/code/spike : sbt
> jetty-restart

Or some such. To get continuous compilation and deployment going you need to do this:

~/code/spike : sbt
> ~ jetty-restart

See the tilde on the second line? That’s it. That sets up file watchers to watch for changed files/resources and executes the specified action when it detects them

Want to run your tests every time the code changes?

~/code/spike : sbt
> ~ test

I’m sorry if you’d like an XML configuration file or something similar. We’re all out of complexity this evening, try again tomorrow.

Back to the Scala & Vaadin.

The next example, from page 40 of the Book of Vaadin is slightly more substantial. I’m hoping that Scala will let us make even bigger improvements to the code because we’ve more to work with.

The Java code:

public class WindowOpener extends CustomComponent implements Window.CloseListener {
    Window mainwindow;
    Window mywindow;
    Button openbutton;
    Button closebutton;
    Label  explanation;  

    public WindowOpener(String label, Window main) {
        mainwindow = main;
        final VerticalLayout layout = new VerticalLayout();
        openbutton = new Button("Open Window", this, "openButtonClick");
        explanation = new Label("Explanation");
        layout.addComponent(openbutton);
        layout.addComponent(explanation);
        setCompositionRoot(layout);
    } 

    public void openButtonClick(Button.ClickEvent event) {
        mywindow = new Window("My Dialog");
        mywindow.setPositionX(200);
        mywindow.setPositionY(100);
        mainwindow.addWindow(mywindow); 

        mywindow.addListener(this); 

        mywindow.addComponent(new Label("A text label in the window."));
        closebutton = new Button("Close", this, "closeButtonClick");
        mywindow.addComponent(closebutton);
        openbutton.setEnabled(false);
        explanation.setValue("Window opened");
    } 

    public void closeButtonClick(Button.ClickEvent event) {
        mainwindow.removeWindow(mywindow);
        openbutton.setEnabled(true);
        explanation.setValue("Closed with button");
    } 

    public void windowClose(CloseEvent e) {
        openbutton.setEnabled(true);
        explanation.setValue("Closed with window controls");
    }
} 

public void init() {
    Window main = new Window("The Main Window");
    setMainWindow(main);
    main.addComponent(new WindowOpener("Window Opener", main));
}

The free floating init() method is supposed to be placed into the Application class.

I’ve removed the comments and done a little tidying up of the structure: people have suggested that by not tidying the Java code in the earlier examples I was doing Java a disservice. I also removed the comments because I believe that comments are, for the most part, an abomination, a crutch that has removed the need for programmers to support their own weight and write clean code. As with most things, I could be wrong. I doubt it, but it is possible. I’m not egotistical enough to believe I’m never wrong. Just very, very rarely. Honest.

Transliteration:

package spike

import com.vaadin.Application
import com.vaadin.ui._

class WindowOpener(abel: String, main: Window) extends CustomComponent with Window.CloseListener {
    var mainwindow: Window = null
    var mywindow: Window = null
	var openbutton: Button = null
    var closebutton: Button = null
    var explanation: Label = null
    mainwindow = main
    val layout = new VerticalLayout()
    openbutton = new Button("Open Window", this, "openButtonClick")
    explanation = new Label("Explanation")
    layout.addComponent(openbutton)
    layout.addComponent(explanation)
    setCompositionRoot(layout)

    def openButtonClick(event: Button#ClickEvent): Unit = {
        mywindow = new Window("My Dialog")
        mywindow.setPositionX(200)
        mywindow.setPositionY(100)
        mainwindow.addWindow(mywindow)

        mywindow.addListener(this)

        mywindow.addComponent(new Label("A text label in the window."))
        closebutton = new Button("Close", this, "closeButtonClick")
        mywindow.addComponent(closebutton)
        openbutton.setEnabled(false)
        explanation.setValue("Window opened")
    } 

    def closeButtonClick(event: Button#ClickEvent): Unit = {
        mainwindow.removeWindow(mywindow)
        openbutton.setEnabled(true)
        explanation.setValue("Closed with button")
    }

    def windowClose(e: Window#CloseEvent): Unit = {
        openbutton.setEnabled(true)
        explanation.setValue("Closed with window controls")
    }
} 

class SpikeApplication2 extends Application {
    override def init: Unit = {
        val main = new Window("The Main Window")
        setMainWindow(main)
        main.addComponent(new WindowOpener("Window Opener", main))
   }
}

I’ve dropped this into a new file on my system src/main/scala/spike/Application2.scala.

To get it to run, you need to change the web.xml. Change the line:

<param-value>spike.SpikeApplication</param-value>

to:

<param-value>spike.SpikeApplicatio2n</param-value>

Yup, there’s a 2 on the end of the class name now. Fire up the app and have a look - we’re going to get pimping!

So, what do I want to change first? Well, if you look where the Buttons are instantiated you’ll see something that made my skin crawl. In an earlier episode I talked about the ugly anonymous inner class usage, but mentioned that it was probably the best choice. Best of a bad lot in Java as it were. This is one of the other choices. The button is being instantiated with a target object and a method name so that the button can call the method when clicked. I know why people do this, I’ve done it myself and in Ruby or Smalltalk it’d be idiomatic, people would be prepared for it, and it wouldn’t get messed up. In Java having method names as strings is always a bad idea. Amusingly, as if my sub-consience was trying to prove me right, I misspelled one of the method names not once, but twice. And when I ran the app.. it didn’t work.

Using method names as Strings and calling them by reflection isn’t a good idea. There are so many things that can go wrong - signature changes, misspellings, changes in visibility level, return type changes, exceptions etc. In Java, the belief that static typing protects you from these sort of problems means that developers just aren’t prepared for it. Thankfully, the SButton class we created earlier solves this problem in a nice type-safe, statically defined way. Goodbye reflection invocation.

One of the ugly parts about using reflection is that the methods you’re calling back to have to be public so that the reflector can see them. This leads to classes with odd “don’t call me I’m not what you think” methods.

This class also implements the WindowListener interface because it needs to respond somehow, and some of the class’ state is modified as a result of the callback. Implementing this interface here was the expedient thing to do, but it does mean that the class has a broader interface, implements an interface so that it can comply with the demands of its own internal workings and, if it wanted to listen to multiple child windows would need to jump through hoops to figure out which child window it was that was being close. I’m gonna get my closure tools out again.

package spike

import com.vaadin.Application
import com.vaadin.ui._

class SWindowCloseListener(action: Window#CloseEvent => Unit) extends Window.CloseListener {
    def windowClose(event: Window#CloseEvent) = {
        action(event)
    }
}

class WindowOpener(private val mainWindow: Window) extends CustomComponent  {
    private val openbutton = new SButton("Open Window", _ => createSubWindow)
    private val explanation = new Label("Explanation")

    private val layout = new VerticalLayout()
    layout.addComponent(openbutton)
    layout.addComponent(explanation)
    setCompositionRoot(layout)

    private var subWindow: Window = null

    private def createSubWindow: Unit = {
        subWindow = new Window("My Dialog")
        subWindow.setPositionX(200)
        subWindow.setPositionY(100)
        subWindow.addComponent(new Label("A text label in the window."))
        subWindow.addComponent(new SButton("Close", _ => closeSubWindow))
        subWindow.addListener(new SWindowCloseListener(_ => onSubWindowClose))
        mainWindow.addWindow(subWindow)

        openbutton.setEnabled(false)
        explanation.setValue("Window opened")
    } 

    private def closeSubWindow = {
        mainWindow.removeWindow(subWindow)
        openbutton.setEnabled(true)
        explanation.setValue("Closed with button")
    }

    private def onSubWindowClose = {
        openbutton.setEnabled(true)
        explanation.setValue("Closed with window controls")
    }
} 

class SpikeApplication2 extends Application {
    override def init = {
        val main = new Window("The Main Window")
        main.addComponent(new WindowOpener(main))
        setMainWindow(main)
   }
}

In the tidy up, we’ve gone from five instance variables down to four ( three of them immutable values), lost a constructor parameter that didn’t do anything, created a nice little reusable listener class, removed risky reflection invocation and removed ALL of the new public methods and properties. The interface of our class is now identical to the interface of our super class.

Jun 30

Some Vaadin at last.

Download Vaadin from here and unpack it. You only really need the minimal one jar download, but with documentation this well written it’d be a shame not to grab it all.

They have platform specific downloads because some pieces of the underlying GWT toolset use SWT. As far as I can tell, there’s no runtime platform specificity and I’m not going to be touching the GWT tools in this series, so don’t worry about it.

From the download copy the vaadin-6.0.0.jar file ( hidden inside the WebContent directory if you downloaded the full installation ) into your spike/lib directory.

SBT adds any jars it finds in the lib directory to the classpath. Old-school styling baby!

And now some code.

The first “why don’t you follow along at home” example from the Book of Vaadin is on page 24.

You need to configure the Vaadin servlet in the web.xml file. Sorry, back to the XML grindstone.

Insert this into the web-app element:

<display-name>myproject</display-name>
<context-param>
	<description>Vaadin production mode</description>
	<param-name>productionMode</param-name>
	<param-value>false</param-value>
</context-param>
<servlet>
	<servlet-name>Spike Application</servlet-name>
	<servlet-class>com.vaadin.terminal.gwt.server.ApplicationServlet</servlet-class>
	<init-param>
		<description>Vaadin application class to start</description>
		<param-name>application</param-name>
		<param-value>spike.SpikeApplication</param-value>
	</init-param>
</servlet>
<servlet-mapping>
	<servlet-name>Spike Application</servlet-name>
	<url-pattern>/*</url-pattern>
</servlet-mapping>

The web.xml will now route all requests through the Spike Application servlet that’s will look for the spike.Application class. I’ve changed the class and package name from the example to match the project and to keep package hierarchies short-ish.

The original Java code on the first example looks like this:

package com.example.myproject;

import com.vaadin.Application;
import com.vaadin.ui.*;

public class MyprojectApplication extends Application
{
    @Override public void init() {
        final Window mainWindow = new Window("Myproject Application");
        Label label = new Label("Hello Vaadin user");
        mainWindow.addComponent(label);
        mainWindow.addComponent(
            new Button("What is the time?",
                new Button.ClickListener() {
                    public void buttonClick(ClickEvent event) {
                        mainWindow.showNotification("The time is " + new Date());
                    }
                }));
        setMainWindow(mainWindow);
   }
}

Not too bad. Particularly when you consider what it generates - a full page of HTML with a button with a server-side call back that displays the server time on screen in an area that fades out after a few seconds.

Not too bad, but I think Scala can do better. Stage 1 - Transliteration.

Create the application class:

~/code/spike : mkdir src/main/scala/spike
~/code/spike : touch src/main/scala/spike/Application.scala

Then edit the class so that it looks like so:

package spike 

import com.vaadin.Application
import com.vaadin.ui._
import java.util.Date 

class SpikeApplication extends Application {
    override def init(): Unit = {
        val mainWindow = new Window("Spike Application")
        val label = new Label("Hello Spike Application User!")
        mainWindow.addComponent(label)
        mainWindow.addComponent(
        new Button("What is the time?",
            new Button.ClickListener() {
                def buttonClick(event: Button#ClickEvent) {
                    mainWindow.showNotification("The time is " + new Date())
            }}))
	    setMainWindow(mainWindow)
   }
}

Start Jetty:

~/code/spike : sbt >jetty-run

Then navigate to http://localhost:8080

Exciting - not so much. Still, the Scala here is pretty much identical to the Java code. It is nice to know that you can take a piece of Vaadin code and translate it without too much trouble. But if the Scala isn’t any better - then Java would be a ’safer’ choice.

Let’s see if we can pimp this code.

Hmm, I don’t like the inner class listener. In Java this is the best choice, in Scala we have more choices. Closures/Blocks/BlockClosures/Anonymous Functions/Lambdas/Anonymous Delegates/whatever you want to call them. to the rescue. We can create a button that takes a closure and never have to write one of those ugly little inner classes again.

Another thing that bothers me is that call to setMainWindow. Inheritance like this makes testing and TDD harder because I’m tied into the way the Application class works. I don’t like that. That’s not a game I’m going to play. I’ve an idea of how to extract us from that hole using abstract traits. But that can wait until I try writing tests.

After removing the inner class, slight blemishes in the rest of the code became more obvious so I’ve done a spot of in-lining and removed a few extraneous braces. I often find that once you can’t see the little pimples until you’ve removed the massive warts. Anyway, the code now looks like this:

package spike 

import com.vaadin.Application
import com.vaadin.ui._
import java.util.Date 

class SButtonClickListener(action: Button#ClickEvent => Unit) extends Button.ClickListener {
    def buttonClick(event: Button#ClickEvent): Unit = {
        action(event)
    }
}

class SButton(text: String, action: Button#ClickEvent => Unit) extends Button(text, new SButtonClickListener(action))

class SpikeApplication extends Application {
    override def init: Unit = {
        val mainWindow = new Window("Spike Application")
        mainWindow.addComponent(new Label("Hello Spike Application User!"))
        mainWindow.addComponent(
            new SButton("What is the time?", _ => mainWindow.showNotification("The time is " + new Date)))
	   setMainWindow(mainWindow)
   }
}

But, but, but, that’s longer I hear you cry. Yes it is. But the first two classes can be pulled out and stored away somewhere and you’re free of inner class event handlers for every button hence-forth.

The important part is the init method, isn’t that much cleaner than before? You create a window, add a couple of components and pass it on.

For my money, this is a win.

Swap this code into place, execute a:

>jetty-restart

and take a look to make sure it hasn’t changed.

Next time - continuous build and deploy and on to the next example.

Jun 30

So, where to start? At the beginning I suppose. I’ve decided to take the Book of Vaadin and, as I’m reading it, I’ll convert each of the examples from Java to Scala. Stage one will be transliteration, stage two will be ‘pimping’ and Scala-fying the code.

My Scala chops are still developing, and my Vaadin chops are non-existant, so if anyone wants to point out stoopid-noob-mistakes or ways to improve my pimping skills please feel free. Either drop me a line here or twitter me @roblally and I’ll try to rectify my mistakes.

As I talk through the process I’ve followed, I’m not going to mention IDE integration. I use the most excellent IntelliJ IDEA and the mostly excellent Scala plugin for it. Configuring the IDE is really outside the scope of this post, you’ll have to figure that out for yourself. Anyway, time to get going.

Stage One : SBT

SBT (Simple Built Tool) is a minimalist (well, it is minimalist now, and more features are arriving all the time) build tool for Scala. It isn’t the answer for every problem, but if things pan out the way I hope they will, it should be good for this little project.

Start off by downloading the SBT launcher : the installation instructions are simple enough.

Stage Zero : Java (preferably Java 6)

Yeah, I know, zero comes before one, but since I’m only going to say “Java - you should have some”, it doesn’t really matter where I put it.

Stage Two : Create a project

Create a directory to hold the project. I’ve used ~/code/spike - using spike in the XP sense rather than the Buffy villain fan-boy sense.

~/code/spike (3504) : sbt
Project does not exist, create new project? (y/N/s) : y
Name: spike
Organization []:
Version [1.0]:
Scala version [2.7.5]:
sbt version [0.5]:
...lots of output...
>

When I ran SBT in the empty directory it told me that there was no project found (anyone who’s surprised should stop reading now.. nothing to see here, move along) and helpfully offered to create it.

I entered the name of the project ’spike’ and hit return to accept the defaults for everything else.

SBT will now download everything I need to get my project going, including the correct version of Scala and SBT itself. Yes, all you downloaded was the SBT launcher, the full version is tied to the specific version of Scala you’re using so it helpfully has a neat layer of indirection.

You’ll notice that SBT has left you with an endearing little ‘>’ prompt. SBT can execute a command, or it can enter an ‘interactive’ mode where it will execute a command and then stay running, waiting to fulfil your next desire. Like a very limited genie, only capable of granting pretty crappy wishes. The scala compiler can take a few seconds to get warmed up, so this isn’t a bad idea. You can also tell it to execute commands whenever it detected file changes - very nice for those TDD aficionados, on every file save you can have all your tests run so you never have to manually poke the run button. When using two monitors I like to have a console with SBT running in file watcher mode running my tests on one monitor with my IDE on the other.

OK, OK, very nice auto test runner… neat but hardly revolutionary. Well, another neat but not revolutionary feature is the ability to run a hosted Jetty instance and restart that whenever files change. I’m hoping that will be a real win when we get to the point of actually having something on the screen.

We don’t want SBT running just now, though so:

> exit
[info]
[info] Total session time: 781 s
~/code/spike :

The default SBT project isn’t a web app, and doesn’t really know anything about them. Let’s fix that.

~/code/spike : mkdir src/main/webapp/
~/code/spike : mkdir src/main/webapp/WEB-INF
~/code/spike : touch src/main/webapp/WEB-INF/web.xml

Open the web.xml file in your favourite editor and pop in:

<?xml version="1.0" encoding="UTF-8"?>
<web-app
	xmlns="http://java.sun.com/xml/ns/javaee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	version="2.5">
</web-app>

My word, I’d forgotten what a pain in the ass it is to try to put sample XML into a blog posting. For that reason, if for no other, I’ll try to keep the XML to a minimum. I think we’ll have to define a single servlet, after that we can stay away from angle-bracket land for a good while.. maybe forever.

SBT is configured using Scala. Adhering to the convention over configuration mantra it has pretty sensible defaults. But since this is a web app, the defaults won’t cut it. We need to create a project configuration class.

~/code/spike : mkdir project/build
~/code/spike : touch project/build/SpikeProject.scala

And pop open SpikeProject.scala file in the editor/IDE of your choice. (We’re almost there.. honest).

import sbt._

class SpikeProject(info: ProjectInfo) extends DefaultWebProject(info)
{
  val jetty = "org.mortbay.jetty" % "jetty" % "6.1.18" % "test->default"
}

And our configuration is done. GENTLEMEN, START YOUR ENGINES! Or, developers of any gender, please start your web-server.

Run the following command once.

~/code/spike : sbt update

You need to do this every time you change your configuration. SBT will download your dependencies, but only when you ask it to. With everything in place

~/code/spike : sbt
> jetty-run

And there you have it! A web application that does nothing at al on http://localhost:8080!!!

Please note that I started sbt in interactive mode and then started Jetty. If you just run sbt jetty-run then jetty starts and promptly stops. Not as useful as you might imagine.

I know, I know, a second part has gone by without any Vaadin and hardly any Scala. Next time, I promise.

Jun 30

Over time I’ve been becoming increasingly enamoured of Scala. Like many technologies that I come to love, the first two or three times I try them I come away unsatisfied. I don’t know what it is, but some technologies keep me coming back until they click. Scala’s been like that. The first time I was put off by the apparent complexity of the syntax, the second time I was put off when I was stymied by the lack of a useable reflection mechanism. This time round… I’m happy and I feel at home.

So, I’ve been looking round at web frameworks in the Scala world, and there wasn’t a lot that pleased me. I can see why some people would like Lift - if it was 1998 and we hadn’t figured out that the only thing worse than having code in your markup, is having markup in your code. Maybe this is another one of those things I’ll come back to and have a click moment on. But, for now Lift goes in the “bad idea that works only because of the brain power behind it” pile.

So I started looking round for something that lined up better with my personal sensibilities. I’ve often been attracted to Echo, and it looked like it might be what I was looking for - a component framework that would let me write only in Java - or in this case Scala. Development of Echo 2 seems to be mostly at an end and Echo 3 is closing in on a production release.

I want to develop now, the “keeping up with Jones’” part of me doesn’t want to use Echo 2 and the “oh, god, the pain” part of me doesn’t want to use a beta release of a framework in an untested configuration.

Poking around the Echo home page, I came across this post mentioning Vaadin. From a development perspective Vaadin looked very similar to Echo - application centric, everything is written in Java, component based. And they’ve just released a new version (6.0) with some outstanding documentation including the very nifty Book of Vaadin.

I’m a sucker for a well documented open source project, so I’m trying it with Scala rather than Java, and I’ll document my experiments here.

Joonas Lehtinen, who I believe has a connection to Vaadin asked me to report to the Scala or Vaadin mailing lists - once I’ve got a couple of these posts up I’ll drop a link into the Vaadin forums.

PS I’m not picking a fight with the Lift people, I respect them and I wish them every success. I’ve bought the Lift Book and David Pollack’s excellent Scala book, so I’m doing what I can to support the community. Even though I think they’re off in the weeds. Dammit, I didn’t mean to type that out loud.

Apr 07

I’ve written here, in the past, about my belief that, by starting an Open Source project, you’re making a commitment to the world. It seems that Rod Johnson of Spring fame and owner of successful Open Source company Springsource agrees with me.

Whilst being interviewed during episode 238 of The Java Posse Rod commented that he felt “Open Source projects, like puppies, are for life not just Christmas”.

Apr 01

Over the last couple of weeks I’ve been exploring and programming in Erlang. It has been an interesting, informative but challenging and frustrating experience.

Do you remember the scene in Young Frankenstein where Gene Wilder, playing Frankenstein and … whoever it was, playing the monster do the soft-shoe-shuffle and sing ‘Putting On The Ritz’? Well, the gag is that the monster, despite his grotesque, clumsy, clumsily-assembled form carries out the dance immaculately until, right at the end he sings his one line of the song. When he howls, “Puttin’ on a riiiitz’ I nearly wet myself laughing. Erlang’s like that.

Erlang is a horrid language, Damien Katz recently pointed out what he considered to be the flaws of the language, and I’d largely agree with his take on things. Actually things are worse than he makes out, he doesn’t critique the documentation which is poor and he doesn’t point out the problems of cruft and half-implemented abandoned features in the implementation. In response to his posting, someone in the comments points out that Erlang does have a package/namespace mechanism which is true. The topic of packages came up last week on the mailing list - someone pointed out that it didn’t seem to work properly. The answer they got was that that was put in as an experiment at the start of the decade, it didn’t work properly and that the implementers might take it back out at some point .. if they got around to it. Other features like module attributes have a similar story.

Katz chops away at some of, what he considers to be, the more egregious ugliness of the language, he doesn’t bother with the minor warts. But I find that there are enough of these warts that they become irksome. For example, macros have to start with a ? which leaves you code looking confused and ugly - why are there so many questions and so few answers? Lisp macros fit in with the language, they are indistinguishable from normal forms and so they create an extensible, grow-able language. Erlang macros stand out, they feel like something you should avoid because they are strange and ugly.

But, all these things said, I still find that Erlang and OTP - like the monster’s dance - has moments of grace, beauty and style. There are things in there to love. Erlang does processes and monitoring better than anything I’ve ever seen, it truly is remarkable in this aspect. If I needed to write an application where concurrency was more important than anything else, I might well look to Erlang.

So, Erlang, I’ve learned from you - I’m a better programmer for having spent a couple of weeks with you. But, for now, all I see is a monster capable of some clever tricks … and you’re going back in the box, until I need you.

Mar 25

I’ve been a fan of Ruby for a long, long time. If I had a real world problem to solve, and language was no barrier .. I’d probably choose Ruby, unless there was a solid reason not to.

Why then do I spend so few of my hacking hours poking at Ruby code?

I think it is because my hacking hours are spent twiddling with new shiny things or working through the same old exercises[1] in different ways, rather than trying to achieve something. As I mentioned a few days ago, I think it is irresponsible and unfair to release an app or library to the OS community unless you’re willing to support it, and I’m not, so I rarely build big projects. For the most part, how I solve the problem is more interesting to me than the problem.

I suppose it comes down to - I rarely use Ruby because I’m rarely trying to solve a problem as efficiently as I can.

[1] Uncle Bob Martin’s “Agile Software Development : Principles Patterns and Practices” contains an interesting little console programming problem that I’ve worked through in half a dozen different languages.

Mar 24

Does anyone remember the final episode of Blackadder Goes Forth? It is the one where Blackadder attempts to avoid being send to certain death by pretending to be mad. He puts his pants on his head and sticks pencils up his nose because .. well, people who do that are obviously insane.

pants_396x222.jpg

I think that Richard Stallman is trying to pull a similar trick with this posting. I appreciate everything the man has done for the software community, but he seems to have transcended reality at this point. Maybe he’s frightened that with the current economic downturn that wold war is inevitable and that he’s going to be conscripted - he’s smarter than us all, and he’s putting his insanity defence in place right now.

Mar 20

I’ve just watched Zed Shaw’s THERE WILL BE PORN: 10 Dangerous Ideas Nobody Should Implement which thankfully contains neither porn, nor ten ideas. He sings, he plays music, he insults people he likes, he has some number of ideas that people should never implement which is less than ten that he talks about and he swears a great deal.

You know the old chestnut whereby both art and porn are hard to describe but “I’ll know it when I see it”. Well, this is neither. But for some reason I enjoyed watching it.

There’s a lot of history you have to have lived through to really understand it; you’ll know if you know. If you do, give his farewell speech a listen. If you don’t … he plays a mean guitar.

Mar 18

This trickle down from Reuters looks and sounds legit.

I’m not sure how I feel about this. Mostly positive I think. Sun has been chasing the client-side dream for the last couple of years ( well forever really, but with renewed vigour of late ) with twaddle such as JavaFX. Personally, I’ve written mostly server side Java. That’s what I expect to continue to do. If I was going to write client side code, I wouldn’t use JavaFX. I can’t think of a single reason why I would choose JavaFX over Flash or Swing or GWT or SWT or … anything.

Sun, who’ve been financially constrained for a long time, have been focussing resources on client side development and that has led to stagnation and lack of drive on the core Java language. Take the complete failure to deliver on closures for example - Sun had other priorities, so nothing happened. IBM sells hardware, lots of back end hardware. They make money out of said hardware and want people to write as many apps as possible for them. I have hope that they can deliver on the sort of roadmap that will make me happy.

I had a conversation with the head of Sun’s R&D department about three years ago. We talked about their hardware platform and the fact that they were producing hardware with massive numbers of processors and cores, and that each of the cores were comparatively slow. This sort of architecture seems ideal for hosting PHP/RoR/CGI/share-nothing apps and kind of poor for hosting Java apps. I asked him if he felt that was true, and what they were planning to do about it. He said, yes their hardware and software sweet-spots had diverged and that they had some ideas about how to realign their offerings. As far as I can tell, things are still the same today.

Don’t get me wrong. I like Sun. They’ve given me lots of free stuff, for a long time, and in return I’ve given them … nothing. That’s not quite true, I’ve had Solaris boxes ripped out and replaced with IBM Blades running Linux. So, I’ve given them less than nothing. Sheesh, no wonder their stock price has gone down the drain.

Mar 16

Damien Katz, and his family, sold their house and lived off their savings so that he could write free software.

His honesty and his story left me, literally, in tears. But truly inspired.

Please watch it.

Mar 15

Trying to get CouchDB set up, I’ve had to install macports. Macports is a neat tool that makes a lot of apps and libraries available for the Mac. Many of these are old-school Unix libraries and it seems that it isn’t just the code that the Macport team wanted to bring to the Mac - they wanted to bring the Unix user experience too.

I downloaded the installer and ran it. It gave me a lovely progress bar that pottered from zero to about seventy percent in 2 mins or so. Then it just sat there. After about twenty five minutes I tried to stop it .. and it said “No, I’m not going to stop”. Before killing it I decided to see if it was doing anything. I opened a terminal and ran top. It seemed that there were multiple rsync processes consuming CPU. Digging around I found that the installer was actually doing something - downloading files from the mother-ship. I decided not to kill it and another 20 minutes later it finished.

Why do people do this sort of thing? If they’d written an installed that flashed up a message saying “This could take a while” I’d be content to wait. Giving me a progress bar that just stops for most of an hour is madness, the worst possible UI decision. Showing me nothing would have been better because then, at least, it wouldn’t have looked broken.

I’m now all stressed because I have code on my system written by people who thought that UI was a good idea. What other insanity do they have in store?

Mar 15

My foray into the World of Erlang continues. I’m excited and energised by the new and interesting things I’m discovering. Learning to think in terms of messages passed between processes isn’t easy, or natural yet; but I’m getting there.

I do have some concerns though. Erlang has been around for a very long time ( in computer years ) and has a few people who date back to the beginning still involved. Many members of the Erlang community are, however, quite new to the language and are working at trying lots of different ideas - some of them new, some of them translations of ideas from other languages.

What this means, for me, is that when I look around for a library to perform a certain task I’ll find a bunch of different options, each with a different approach, none of them are stable and none of them have any strong hints about their future. It seems that Erlang is such a fertile place for experimentation, and the community is so young, that projects spring up, are used briefly and are abandoned before they reach their potential.

Take web-frameworks for example. I want a UI for an app I’m considering and a web-ui would be just-the-thing. I looked around and there are loads of different web frameworks and web servers. I don’t have any trust that any of them will be actively maintained three years from now. I can’t create a critical dependency between my work and a project that may or may not have a future.

I’m not criticising people for their efforts (I will in a moment though) people are entitled to spend their time and efforts in whatever way they want. Erlang has drawn innovators, early adopters and those dissatisfied with the tools and options they had elsewhere. The relatively blank canvas is, I’m sure, what attracted many people to the language. There’s new ground to be broken, clean slates to be drawn on and blank sheets to be filled with ideas. All wonderful stuff.

The problem I have isn’t with innovation and creativity. The problem I have is with people who innovate, create, persuade other people to use what they are creating and then get bored and forget it. If you write up some code, dump it on git-hub and say “world, it is there if you want it” that’s one thing. If you create a project, put together a pretty project page telling people why it is cool and why they should use it then you’ve created a social contract you’re obliged to support your work. If you don’t want to make the commitment then don’t act like you are.

People who create, advertise and evangelise, then abandon open source projects are doing the world an active dis-service. Why?

  • There’s only so much time and attention to go round. Many/most projects are not original - they’re similar to other existing projects. By creating an only slightly divergent copy of something you dilute the market of the original, reducing their chances of success.
  • Open Source has, in most fields, killed off the market for commercial products. I don’t have the choice to pay someone for a quality product because the market has been devalued. Killing off the commercial market and replacing it with nothing is a distressing scenario.
  • It provides an impediment to those who might follow through on an idea. Many in the Open Source community dislike the idea of forking or creating copy-cat projects. If you create an abandon-ware project you’ve added an extra barrier for others to cross.

Just to be clear here. I don’t have a problem with Open Source. I’ve used it for many years. I’ve spent some of the last few years providing technical support for Open Source applications and libraries. I’ve found good Open Source projects to be, without question, the equal of their commercial counterparts. I’ve watched innovation and change come from the Open Source community, positively affecting the entire industry. I like Open Source. I get annoyed by Open Source dilettantes and their here today/gone tomorrow behaviour.

I have an Open Source project of my own. I’m not going to point to it, because I don’t want you to use it. I made the code available for myself and a couple of other people. I have a disclaimer on it saying “there’s no good reason for you to use this” because it is treading old ground and I’m not going to maintain it. If someone finds it and uses it .. that’s fine, if nobody ever does that’s fine too. But nobody will ever believe that it is a project they can depend on.

So what’s my point?

The Erlang community right now has many smart people in it. They have lots of ideas and they want to try them out. There’s almost as many ideas as people, so there are mostly small communities and unstable projects. There’s certainly exceptions to this rule such as CouchDB and RabbitMQ, but in general I don’t see many significant communities building significant projects. For my benefit, and that of everyone else, I’d like that to change.

If you’re about to create a project or release some code you have as an Open Source project, please consider these question:

  • If you have an idea that you’d like to try out, could you do it under the banner of an existing project?
  • If you want to build a product, just like X. Could you contact the people who build X and help them out? You’d probably end up with something better than either of you could on your own.
  • If you just want a creative outlet, do you have to start from a blank slate or would working with a community on something in existence be fulfilling?
  • Would picking up someone else’s abandon-ware and carrying that forward be viable?
  • Are you really going to devote the time necessary to maintain this for the next n years? Where n is a number that at least twice as big as you’d expect.
  • Do you just want to show people something cool that you bashed together? If so, have you made it clear that this was just a one-off that you’ve made available to that people can learn from it or carry on if they’re interested?

Whatever else people may tell you, Java has been a success because of the communities associated with it. In particular the Apache Jakarta community was instrumental in making Java the phenomenon that it became. They had rules, they had standards, they had ethics and lots of smart people talking and building great things. Companies and individuals would adopt projects because they were Apache products - it was a name you could trust. The name and the community had respect and trust. Smart individuals looking to work on interesting problems gravitated there. Those with interesting ideas would go there and find other like-minded people to help them.

Erlang doesn’t seem to have that community, not yet anyway. But it does have enough people to create that community. At the moment they’re consumed by experimentation, and there is no central place or group that seems to be a likely candidate. Some languages never coalesce around a community and are forever fragmented and experimental e.g. Smalltalk. This isn’t necessarily bad, things are what they are.

Right now, I’m enthusiastic and energised, but I’m also cautious and concerned. Erlang looks like it could be ideal for the problem I want to solve; I just don’t think I trust the basket enough to put all my eggs in it.