Monday, February 22, 2010

Problems and Opportunities

There's no such thing as problems, only opportunities

There may be people and situations for which this is true: tow-truck operators and plumbers come to mind. But for the rest of us, it's critically important to tell the difference — in fact, that is the difference: criticality. Opportunities are optional, problems aren't.

I'm not sure where the “no problems” slogan came from, but I suspect a half-asleep MBA student in ECON 101. In economics, there truly are no problems, nor opportunities either, only choices. But every choice has an “opportunity cost,” which, confusingly, is the net profit from the best alternative. If you (like many business students) don't think of the possibility that net profit can be negative, it's an easy step from cost to slogan.

Houston, we have an opportunity

In the real world, however, net profit can be negative. And when you're a quarter million miles from earth, with limited oxygen and electricity, the opportunity cost of the wrong choice is death. In the computer industry, we're not likely to face such drastic costs; but that doesn't mean we don't have problems.

Wednesday, February 17, 2010

JavaFx: What Niche does it Fill?

I've had fun playing around with JavaFx. I can't shake the feeling that it's in the same situation as Java was in 1996: targeted to a specific niche, but much more useful as a general-purpose language. Unfortunately, everything I've seen says that Sun (Oracle) intends to keep JavaFx in the RIA niche, a competitor to Flash and Silverlight.

And if that's their plan, here's my response: ain't gonna happen. Flash got to its position of ubiquity not so much because of technical merit, but because Adobe has mindshare among the graphical designers who are — like it or not — the arbiters of what goes on the web. At best, these people think of Java as “something to do with JSPs”; at worst, they think of applets (or more likely, negative folklore about applets, because they've never actually seen one). JavaFx is as likely to replace Flash as The Gimp is to replace Photoshop.

More important, Flash itself may not have much longer to run: there seems to be a strong backlash against plugins. Apple, with the iPhone and iPad, is the leading edge of this movement. However, the same attitude is showing up in desktop browsers, as you can see from the many pages describing how to make Java work with Chrome (I spent a half hour trying to get the latest Sun JRE to work with Chrome on Linux, but eventually gave up; call this statement sour grapes if you wish).

Instead, I think RIAs will be built with HTML (5) and JavaScript. This is, again, something very familiar to web designers. Most seem to go the route of raw HTML plus a library such as JQuery, but libraries the Google Web Toolkit and Yahoo UI will probably be more useful to the application (versus web) developer.

But, what about the mobile market? After all, the JavaFx tagline is “all the screens of your life,” and they've certainly made an effort to create one platform to span desktop and mobile applications. However, as you dig a bit deeper, you find that mobile device support is not quite ready for prime time: “Sun is working with Mobile Device Manufacturers and Mobile Operators to enable out of the box support for JavaFX.” What of the billions of Java-enabled handsets already out there? It appears that they're out of luck (although I haven't actually tried running a JavaFx app on, say, a Motorola RAZR). And, just in case you missed it, JavaFx will never find its way to the millions of iPhone users.

To wrap up: I believe JavaFx has a bleak future if it's confined to the RIA and/or mobile markets. But those aren't the only markets out there, and there's no reason that JavaFx has to remain confined. As I wrote when I started this blog, I like Java because it has a simple yet very powerful mental model, and the JavaFx language seems to have the same characteristics. It encourages a functional style of programming while still being object-oriented. There are, of course, other languages that do the same thing; Scala, for example. But those other languages don't have the Oracle marketing department behind them.

There's a lot of discussion about how Java is to evolve. But language evolution is a tricky thing. I could easily do without the mess that is auto-boxing; other people feel the same way about generics. And C has remained essentially unevolved since the 1970s, yet is still very useful (albeit in limited niches).

So I'll end with a question: will Java continue to acquire cruft, or is JavaFx the future?

Tuesday, February 16, 2010

JavaFx: Threading

If you're thinking of writing server-style applications with JavaFx, threading appears to be a problem. The first hurdle is that JavaFx programs run on the AWT event dispatch thread — which makes sense for a GUI. Unfortunately, server applications often run in a “headless” environment, and there are some AWT classes that shouldn't require a graphical display yet still like to throw if they don't have one. Which means that, if some of those classes are buried in the JavaFx runtime, you won't be able to run server applications period.

Assuming that you get past the headless issue, it shouldn't be too difficult to create a background thread (either by creating a thread directory, or via javafx.async.JavaTaskBase) and start a Java server application such as Tomcat in that thread (I say “should” because I haven't tried this). That Java application could then invoke non-GUI JavaFx classes, perhaps one that implements javax.servlet.Servlet, as I described in the previous post.

However, I think there are dragons lurking here. The only reason that you'd want to implement a servlet via JavaFx is to exploit language features such as data binding. Looking at the generated bytecode, however, I haven't found any synchronization and I've seen a lot of static members. In a multi-threaded environment like an app-server, this seems to be an invitation for data corruption.

I'm also somewhat disappointed at the threading support for writing GUI apps. As I've written elsewhere, long-running operations should execute outside of the event dispatch thread. The javafx.async package provides two ways to run such code: the first is JavaTaskBase, which as its name indicates, is meant to run code written in Java (and said code is not allowed to invoke JavaFx classes). The second approach is via Task, which is not terribly well documented (“does not define how to specify the code to run”), and appears to be meant for internal use by API classes such as

Speaking of (which is not found in the provided I ran the example provided in its class documentation, with the addition of printing the current thread for each of the callbacks it defines. And discovered that the callbacks were not executing on the event dispatch thread, so shouldn't be allowed to update GUI components. As I said, there are some dragons here.

On the positive side, when I look at the provided source code, I note that Brian Goetz (author of Java Concurrency In Practice) is listed in the @author tag for many classes. I can only hope that this association is ongoing, and that he gives some thought to JavaFx concurrency in practice.

Monday, February 15, 2010

JavaFx: Integrating with Java

JavaFx applications run on the JVM, which means that they must use class file formats that are compatible with those produced by the Java compiler. Which in turn means that JavaFx code should be able to call Java code and vice-versa. And, in fact, JavaFx to Java integration is easy:

import java.lang.Math;

var a = 12;
var b = 13;
var c = Math.min(a, b);

var d = "this is a test";
var e = d.replaceAll("a test", "an example");

Because of type inference, variables a and b are known to be integers, which are represented internally as int (not, as you may expect, as Integer — although that's no doubt an implementation detail and subject to change). This means that they can be passed directly to the Java method Math.min(). Similarly, variable d is known to be a java.lang.String, so you can invoke instance methods defined by that class.

Calling from Java into JavaFx is a little more difficult. Executing a script from a Java method is not practical: there are a number of methods that you must invoke, and the specific names and call order is undocumented. Script functions are compiled as public static methods, so you could theoretically import the script class and call these directory. However, any non-trivial script function would rely on script variables, which brings us back to the issue of setting up context.

JavaFx classes, however, are compiled as public nested (static inner) classes of their defining script. Which means you can instantiate a JavaFx class from within Java code. However, all of the instance variables will be set to default values — and the setter method names are, of course, implementation details and subject to change. Worse, NetBeans doesn't recognize that the compiled class exists, and flags your Java code as an error; you have compile manually (I didn't try Eclipse).

That leaves instantiating a JavaFx class from within JavaFx code, and passing it to a Java class for use. This is surprisingly easy, although convoluted. You first create a Java interface:

public interface CallbackIntf
    public void callback(String param);

A JavaFx class can then implement that interface:

class MyCallee
extends CallbackIntf
    override function callback(param : String)
        println("callback invoked: {param}");

Next, you instantiate your Java object from within the JavaFx script (in this example, Callback2), and then you can call a method on that object. Incidentally, note that we use new to instantiate the Java object, and can pass arguments into its constructor.

var caller = new Callback2("test");
var callee = new MyCallee;
caller.makeCallback(callee as CallbackIntf);

Convoluted, yes, but it offers promise: many framework objects (eg, Servlet) are specified as interfaces. If you're writing apps that could benefit from JavaFx language features (such as data binding), it's theoretically possible to do so and deploy into a Java framework. In practice, however, I don't think it will work. Threading is one reason, and that's the subject of my next post.

Friday, February 12, 2010

JavaFx: Building a GUI

JavaFx is targeted toward building graphical applications, and you'll find plenty of tutorials that walk you through such apps. Given this focus, I felt I should at least touch on GUI features.

Building the Containment Hierarchy

In a traditional Swing application, you start with a top-level window (a JFrame, or JApplet, or JDialog), and programmatically build out a “containment hierarchy” of components. For example, you'd build your main menu by instantiating a JMenuBar, then instantiating JMenu instances and adding them to it. For each JMenu instance, you'd then instantiate and add JMenuItem instances for the various menu choices. All Swing programs have a similar structure, which means there's a lot of boilerplate code. You could theoretically define the entire containment hierarchy as, say, an XML file, and eliminate the boilerplate. However, in practice you need to link together components and apply rules: for example, a menu item that should only be enabled when there's data for it to process.

A JavaFx application, however, is a step closer to declarative GUI design: the containment hierarchy (JavaFx calls it a “scene graph”) can be specified as a nested object initializer:

Stage {
    title: "Hello",
    width: 250,
    height: 80,
    scene: Scene {
        content: [
            Text {
                font : Font { size : 16 },
                x: 10,
                y: 30,
                content: "Hello, World"

The top level of the scene graph is the Stage. Unlike Swing, which uses different top-level classes for stand-alone applications versus applets, JavaFx uses Stage everywhere. As with other JavaFx GUI classes, Stage presents a much simpler interface than its Swing equivalents: a single scene for content, and a couple of callbacks for high-level events such as closing the window.

There are a couple of things that may not be obvious from this example. First: because the scene graph is constructed using an object initializer, you can extract parts of the initialization into variables — even bound variables:

var curText = "Hello, World";

Stage {
    // ...
                content : bind curText,
    // ...

The other important thing is this: creating a Stage creates and displays the window representing that stage. Swing, by comparison, separates construction and display. In the example above, we called the constructor without assigning the result to a variable. For simple applications, this is all you'll normally do. For more complex applications, you may construct multiple Stages, or hold onto them via variables so that you can modify them while the program is running.


Layout is one of the biggest pains of Swing programming. The Swing layout managers are all based on the idea that you need to position components mathematically, in order to deal with differing display resolutions and/or user actions (such as changing the size of a window). The result, more often than not, is an ugly UI. Or, alternatively, a custom layout manager that better suits the goals of a UI designer (I have several almost-complete articles on Swing layout, including a how-to on writing a layout manager; keep watching my main website feed to see when they appear).

JavaFx provides only a few, very basic layout managers. Most of the examples and tutorials use explicit layout: you provide the X and Y position of the object, and if needed, its width and height. There's also an option to extract layout information into an external CSS file. I haven't tried this, and am not certain why you'd do this; perhaps to deal with displays that have differing resolutions?


JavaFx responds to user actions just like any other GUI environment: it invokes callbacks. If you've spent much time writing Swing ActionListeners, you'll probably like the fact that JavaFx supports first-class functions that you can specify as part of declarative initialization. If you've spent much time with JavaScript, you'll probably hate the fact that those functions are strongly typed, meaning that you have to specify parameters that you may never use.

JavaFx has a much simpler set of actions than Swing, and you can only attach a single function to a particular action. But be honest: how often did you actually use a list of listeners in Swing? Or intercepted Document events rather than just calling getText() on a field?

As I mentioned in my previous post, I think that bound fields will eliminate a lot of the code inside an action. As an example, consider a name/address form, along with a button that writes the form's contents to a database. In a traditional Swing app, that button's action handler would have to explicitly retrieve the contents of every field on the form, use those values to populate an object, then pass that object on to the database. With JavaFx, you could bind the fields of the object to the fields on the form, and the action would simply submit the already-populated object (although if the object's fields remained bound, the user could continue to update them — perhaps JavaFx could benefit from a value-based copy constructor).


A scene graph is a tree of javafx.scene.Node objects, with the Scene at the top, and various combinations of grouping and rendered components under it. The CustomNode class allows you to create new combinations of components that occupy a place in that hierarchy. For example, a field object that consists of both a label and a text field, with consistent sizing.

Note that I said “create”: one of the anti-patterns of Swing programming is to subclass JPanel just to add components to it (that anti-pattern is the topic of another forthcoming article on my website). When you subclass CustomNode, you are actually creating a controller class. You must override the abstract function create() to build out the node's containment hierarchy.

Graphics and Animation

JavaFx provides a simplified interface to the Java2D library. In Swing, if you want to access the drawing primitives, you must subclass a Swing component (usually JPanel) and override its paintComponent() method. JavaFx gives you components that already do this; you simply create a node in the scene graph. You specify the object's position, size, stroke, fill, and transforms in its initializer.

Graphical objects and data binding come together in JavaFx animation. Here's a simple countdown timer, with explanation to follow:

var counter = 10;

Stage {
    title: "Countdown",
    width: 100,
    height: 40,
    scene: Scene {
        content: [
            Text {
                font : Font { size : 18 },
                textOrigin: TextOrigin.TOP,
                x: 60, y : 10,
                content: bind counter.toString();

Timeline {
    keyFrames: [
        at (10s) {
            counter => 0 tween Interpolator.LINEAR;

The scene graph is simple: a single text field. Its content is bound to the variable counter; every time that variable gets updated, the text field will be updated as well. Where this program gets interesting is the Timeline object, particularly its keyFrames property.

A Timeline is like a javax.swing.Timer on steroids. You tell it the desired value for one or more variables at fixed points in time, along with a way to interpolate between the starting value and the desired value, and the Timeline will make that happen. Here I specify that, at 10 seconds after the timeline starts, the value of counter should be zero, and that it should change linearly. I start with the value 10, the Timeline constantly invokes the interpolator to compute the “current” value, and then sets the specified variable (which is in turn bound by the text field).

Animation is considered such a big deal that the at operator is a part of the language. As far as I can tell, all that it does is instantiate a KeyFrame object. Unfortunately, the Animation chapter of the Language Reference is currently empty. As a result, figuring out animations is a matter of looking at examples and experimenting.


One of the problems with J2ME development is that you don't have the full Java environment: there's no floating point, and a very limited subset of the API. JavaFx attempts to rectify this, but even so, its API breaks out into two categories: common and desktop. The desktop profile provides OpenGL graphical effects (the entire javafx.scene.effect package), as well as the ability to use Swing components.

This Isn't Your Father's GUI

Looking through the API docs, I was struck by what's missing: there aren't any menus. Nor tables. This is intentional: as I learned from a HanselMinutes podcast, the JavaFx team is not trying to build the next toolkit for corporate applications. Indeed, looking at what they've done, I hear “mobile app”: a simplified UI, with flashy controls, designed to fit in a small space. Which is not a bad thing.

Wednesday, February 10, 2010

JavaFx: Bound Variables

One of the things that I find most interesting about the JavaFx language is binding: you bind a variable to an expression, and the value of the variable changes whenever the expression changes:

var a = 12;
var b = bind 2 * a;

a = 17;

In this example, the value of b starts out as 24 — 12 * 2. However, when a is updated, the value of b changes: it's now 34.

Binding is implemented using an Observer pattern, rather than lazy evaluation: b is recalculated at the time a is changed (the compiler attaches a “listener list” to all variables involved in a bound expression). Functional purists may be muttering under their breath at this point, but this approach does allow a couple of interesting features.

First, it means that the runtime does not need to completely re-evaluate a bound expression: the compiler memoizes sub-expressions, and only recomputes those that depend on the changed value. This can be useful if the bound expression includes a long-running function:

function longRunningFunction() {
    println("longRunningFunction() invoked");

var a = 12;
var b = bind a * longRunningFunction();

a = 13;

Second, it means that you can create bidirectional binds, in which changing the value of either variable will change the other. This can be useful if you have two linked input fields:

var x = "foo";
var y = bind x with inverse;

println("before change, x = {x}, y = {y}");
y = "bar";
println("after change, x = {x}, y = {y}");

Binding isn't limited to discrete variables. You can pass a bound expression into a class initializer, and that particular instance of the class will be updated as the expression changes:

class MyClass {
    var x : Integer;

var a = 12;
var b = MyClass { x : bind a };
var c = MyClass { x : a };

println("before change: b={b.x}, c={c.x}");
a = 13;
println("after change: b={b.x}, c={c.x}");

When the class is a GUI object, binding becomes a low-effort way to implement MVC: simply bind the relevant fields of the GUI object (view) to the relevant fields of the model object. Having written more than my share of event listeners and active models, this approach seems very civilized.

Binding does, however come with a performance hit: I wouldn't want to bind to a variable that will be updated frequently. And I can imagine a program filled with “spaghetti binds” that are impossible to untangle. It's like any new feature: “with great power comes great responsibility.” I'm sure we'll go through a phase of gratuitous binding, but once programmers get that out of their system we'll have programs that are easier to maintain.

Tuesday, February 9, 2010

JavaFx: Interesting Language Features

Today's post takes a look at a few of the JavaFx language features that I find interesting. It's by no means an exhaustive rundown of the language; for that, take a look at the language reference (I expect this link to change at some point in the future — right now it points to a build system). And the most interesting feature, binding, will be the topic of its own post.

This is going to be a long post, so get a cup of coffee.


A JavaFx source file is called a “script,” and looks a lot like a JavaScript source file: unstructured, with variable definitions, functions, and inline executable code all jumbled together. But, as I noted earlier, this “script” is actually compiled into a Java class.

This class definition has a lot of boilerplate in it to bridge the gap between features of JavaFx and JVM bytecode. All of this boilerplate is, of course, implementation dependent and subject to change. One piece is the static method javafx$run$(), which serves the same function as Java's main(); the javafx program looks for this method when it starts a JavaFx application.

Another implementation detail, and one that I think is a little disturbing, is that all of the script's variables and functions are represented as static class members. I suspect that this detail is driven by the idea that scripts a primarily used for initialization of the GUI, and most action takes place in classes.

Class Members and Initialization

Unlike Java, but like JavaScript, classes are happy to expose their internals: the language includes access modifiers, and the language reference indicates that the default is script-level access, but the generated code says that everything is public.

Rather than providing constructors, you initialize instances using an “object literal” notation that's very similar to JavaScript's object literals:

class MyClass {
    var a : Integer;
    var b : String;

var z1 = MyClass { a: 123, b: "456" };

There's no new! And I should mention that JavaFx is very liberal with regards to delimiters in an object initializer: here I separated my initializers with a comma, which follows the JavaScript practice. However, I could have used a semi-colon, or simply omitted the delimiter altogether; the JavaFx compiler would recognize where each item ended. I still haven't figured out all of the rules, so simply follow Java practice: semi-colons at the ends of statements, and commas between items in a list.

Mixin Inheritance

The Java inheritance rules are imposed by the JVM: a given class may have only one superclass, but may implement any number of interfaces. JavaFx appears to bend the rules : you can create “mixin” classes, similar to Scala traits, and a JavaFx class can extend more than one mixin:

mixin class Foo {
    var x : Integer;

mixin class Bar {
    var y : String;

class Baz
extends Foo, Bar {
    override function toString() : String {

var a = Baz { x : 123, y : "456" };

Of course, JavaFx doesn't break the rules: the JavaFx compiler translates mixins into composition. The Baz class actually holds instances of Foo and Bar, and has getter and setter methods that delegate to those instances. Incidentally, you won't find mixins in the current language reference; you need to go to the tutorials.

This example shows one additional feature of inheritance: you have to explicitly override member variables and methods. Here we implement a custom toString() method. Since that method is already defined by java.lang.Object, which is the ultimate ancestor of any JavaFx class, we need to mark it as explicitly overridden. As far as I can tell, this is simply a means of error-checking, similar to Java's @Override annotation; JavaFx does not impose “final unless defined otherwise” semantics.

Variables, Definitions, and Type Inferencing

In the class examples above, you saw the canonical variable declarations:

var NAME : TYPE;

At first glance, this appears to be a case of the language designers wanting to look like ActionScript and not Java; it's semantically equivalent to a Java variable declaration, which puts the type first. However, JavaFx also supports type inferencing: you can declare and initialize a variable at the same time, and the compiler will figure out what type you're using:

var a = "foo";
var b = a;

For people tired of constantly repeating long variable declarations in Java, type inferencing is a godsend. For people used to JavaScript, which doesn't have strong typing, they may find type inference annoying:

var a = "foo";
a = 123;        // this won't compile

To close out the discussion of variables, I'll note that JavaFx also provides the def keyword, which is similar to Java's final modifier:

def x = 123;
x = 456;        // won't compile

I'm dubious regarding the value of def. With multi-threaded programming, it's very useful to declare that a “variable” is actually immutable. Scala, for example provides the val keyword to do this. However, the JavaFx def keyword does not imply immutability: it can reference a bound expression, which may change during runtime. Until the language matures, and develops truly different semantics for def versus var (and I'm not sure what those might be), I plan to stick with var for all variables.

Blocks Have a Value

Most “curly brace” languages use those braces to make a group of statements syntactically equivalent to a single statement. For example, in Java:

for (int ii = 0 ; ii < 10 ; ii++)
    System.out.println("this is in the loop");
System.out.println("this isn't");

for (int ii = 0 ; ii < 10 ; ii++) {
    int zz = 12 * ii;
    System.out.println("this is in the loop");
    System.out.println("as is this");
System.out.println("this isn't");

Blocks also introduce a new scope for variables: in the example above, the variable zz is only accessible from code within the block. In JavaFx, blocks have an additional feature: the last expression in the block becomes the value of that block:

var z = {
    var x = 10;
    var y = 20;
    x + y;

Interesting, but what's the point? Well, consider that in JavaFx the the if keyword introduces an expression, not a statement. So you get the following formulation of a ternary expression:

var x = 12;
var y = if (x < 20) {
            var z = x / 2;
            z - 17;
        else {

And not only is if an expression, but for is as well. Which is particularly useful when generating sequences (the JavaFx equivalent of an array):

var seq = for (x in [1..5]) {
              [x, x*x, x*x*x];

Explaining that last example would be a blog posting on its own. I suggest however, that you try it out if you've downloaded a development environment.


Closures are a hot topic in modern programming languages. As C programmers have known for decades, function pointers are an incredibly powerful tool (Lisp programmers have known this for longer, but such knowledge is indistinguishable from their general smugness). A big benefit of function pointers is that they let you abstract away a lot of boilerplate code, particularly in the area of resource management. For example, here's a typical piece of Java database code:

        Connection cxt = DriverManager.getConnection("url");
        PreparedStatement stmt = null;
             stmt = cxt.prepareStatement("sql");
             ResultSet rslt = stmt.executeQuery();
             // process result set
        catch (SQLException ex)
            // do something with the exception
            if (stmt != null)
            if (cxt != null)

That boilerplate try/catch/finally must be repeated for every single SQL statement that you execute. And as written, it has a bug: the call to stmt.close() can throw, in which case the Connection will never be closed. If you cache PreparedStatements, the code becomes even more complex. With first-class functions, you can implement the boilerplate in a DatabaseManager class, and define a function that just processes the result set:

var dbManager = DatabaseManager { /* config */ };
            function(rslt:ResultSet) {
                // process results here

In this example, we create a new function object as an argument to the executeQuery() method. This method can then call the function, passing in the ResultSet that it gets after executing the query. Once the method finishes, the function will be garbage-collected.

The example above is a bit abstract, so here's a simple compilable script:

var fn = function(x, y) {
    x + y;

var z = fn(12, 13);

Here we define a variable, fn, that holds a function. We then execute the function, storing the result in variable z. We could have passed the function call directly into println(), and we could pass the function itself to some other function.

But wait, there's more! JavaFx implements true closures, where a function has access to the variables defined in its enclosing scope:

var a = 17;
var b = 23;
var c = function()
            var t = a;
            a = b;
            b = t;

println("before swap: a={a}, b={b}");
println("after swap: a={a}, b={b}");

Personally, I don't particularly like closures. You could invoke c from any point in the code, perhaps in a completely different script; this is a great way to make your program behave in an indeterminate and hard-to-debug manner. In cases where you actually want the ability to update script variables from somewhere else, binding is probably a better option; I'll write about that tomorrow.

To close out this post, I want to note that JavaFx does not support lazy evaluation of functions. To my mind (if no-one else's), that's a big part of what makes a “functional” programming language: you can pass a first-class function to another function that expects, say, an integer, and the passed function will be evaluated when needed to provide the value.

Monday, February 8, 2010

Getting Started with JavaFx

As my last posting noted, I'm intrigued by the JavaFx language. It's being marketed as a platform for Rich Internet Applications (RIAs), in competition with Flash (Flex) and Silverlight. I don't think it's going to be successful in that space, for reasons that I'll detail in a future post. However, it might just be the next big language for the JVM platform, a functional-object language with the marketing muscle of Oracle behind it.

With that in mind, I'm taking some time to investigate the language, and will be writing a series of posts about it. I won't spend a lot of time on the GUI aspects; there are already blogs that do that, and a whole page of examples with source code. Instead, I want to point out some of the things that I think are neat about the language, and some of the roadblocks that might be in its way as a general-purpose environment.

There will be a few code snippets along the way. You can compile and run them from the command line, using the javafxc and javafx tools from the SDK. There's also IDE support for NetBeans 6.x and Eclipse. I use the NetBeans plugin, and it seems fairly solid (although there seem to be some issues with NetBeans on Ubuntu 9.04 — sometimes it stops accepting keystrokes until I switch windows). If you don't already have NetBeans, you can download it pre-configured with JavaFx, from the JavaFx downloads page (and you'll find the SDK there too).

Before diving into code, there are a couple of terms that have special meaning with JavaFx:

A JavaFx source file. Although called a “script,” these files must be compiled into Java bytecode, and run from within the JavaFx environment. Scripts are translated into top-level Java classes with predefined methods used to invoke the script (think of main()), along with the various methods, variables, and code defined by the script.
Much like a class in any other language: a definition that combines data and methods, and must be instantiated for use. JavaFx classes are defined within a script, and the compiler creates nested Java classes to represent them.

Now it's time for “Hello, World”:

package experiments.language;

println("Hello, World");

That's it. It really does look like a script: there's no boilerplate class definition, no public static void main definition. Even the println() statement gives no hint that it's actually implemented by the class javafx.lang.Builtins.

All of this, however, is simply syntactic sugar: you could easily write a precompiler that takes a similar script and adds the boilerplate Java code. I'll leave you with something new, however: inline variable substitution, a la PHP:

package experiments.language;

def addressee = "World";
println("Hello, {addressee}");

Thursday, February 4, 2010

Book Review: Essential JavaFx

I recently received a copy of Essential JavaFx as book give-away at my local Java Users Group meeting. The JUG receives such books directly from publishers, with the expectation that JUG members will write reviews. My review of this book follows; I suspect that Dave won't be sending it back to the publisher.

My bookshelf holds a dog-eared copy of The UNIX C Shell Field Guide, written by Gail and Paul Anderson in 1986. To me, it represents the perfect mix of tutorial and reference, presenting an enormous amount of technical detail in a careful progression. Unfortunately, I can't say the same for their book Essential JavaFx: the material is disjointed, skimming the surface of many topics in seemingly random order, without truly examining any of them.

This book begins, as nearly all programming books do, with a simple “Hello, World” example. This part is, in fact, a little too simplistic: it walks the reader through specific screens and buttons of the NetBeans IDE. The actual program appears only as a screen-shot, without explanation of its structure. For a book that is targeted to an audience with “some previous programming experience,” this is disappointing: I want to see the program, not the IDE.

Chapter 2 attempts to remedy that initial surface treatment, by presenting a relatively complex example application. And it starts well, with a description of the way that a JavaFx application is built around a “scene graph,” and the admonishment to “think like a designer [...] visualize the structure of your application.” But then, it dives into variable definitions and control constructs, without so much as mentioning how they fit into the scene graph. And from there, the same chapter touches on accessing Java classes, visual effects, lazy expression evaluation (not identified as such), and animations &mash; a few paragraphs or pages for each, without explanation as to how they might fit together in an application.

Chapter 3 is a whirlwind treatment of the core JavaFx language. And there is a lot to this language: it is far closer to Scala than to Java, with influences from Python. Indeed, I could envision an entire book exploring the effective use of these core language features, perhaps even ignoring the GUI.

The subsequent chapters are much the same: quick hits without real content. Chapter 6, “Anatomy of a JavaFx Application,” is the closest that we get to a step-by-step tutorial, yet even here the Andersons forget their early advice: rather than starting with the application structure, they immediately create component subclasses, and only later assemble them into a scene graph.

In the end, I put the book down and turned to my IDE and “experiential learning.”

So, not so great a review of the book. But the language looks fascinating, and I plan to spend time working with it over the next few weeks. My first impression is that it might in fact be “the next big language” for the JVM: it seems to be a nice combination of strong typing, declarative configuration, and functional/object execution. I'm wondering if, like Java before it, JavaFx might be introduced to the world as a GUI language, yet end up as a language for server-centric applications.