Archive for May, 2007

Java 6 on Mac OS X - When?

Wednesday, May 30th, 2007

Developing Java apps on Mac OS X is pretty nice in general: The tools are as good, if not better than other platforms (having a proper command line beats Windows any day); compiling and execution runs fast enough; and the hardware and the OS itself is a pleasure to use.

My only complaint, and one that is getting a bit of noise, is that there is no production release of Java 6 available. Sure, there is a preview version from months ago. But the final version has more than a few differences in the API, and I’m guessing a stack of defect and performance fixes as well.

The rumor is that Apple is not releasing Java 6 till Leopard ships (around October). Supposedly so Java 6 on OS X will support the Leopard look and feel. Which is a pain in the neck - I couldn’t care less if Java 6 looks like Leopard. To be honest it’s a pretty small minority that must use it as a runtime environment. However OS X must get a lot of use as a development environment. Most of the development I do is for apps that are going to run on Windows anyway. Surely Java 6 could just be released first, and then a separate look and feel plugin for Leopard released after the fact? (it’s not like that is all that hard with Swing)

The rumors about Leopard are just that - rumors. There hasn’t been anything official from Apple saying what the release schedule looks like.

Simon Brocklehurst sums it up:

What is particularly frustrating, however, is that Apple remains totally silent on their Java strategy. When will Java 6 see a production release on MacOS X? With the Leopard release? Somtime in 2008? In 2015? Never? No-one has any idea; and Apple isn’t talking - not to developers; not to customers; not to anyone.

Now, however, the OpenJDK project is… well… open! The Java platform is moving full steam ahead to Open Source under the GPL. All of which begs the question is: will the Apple developer community decide to build their own up-to-date version of Java that runs on MacOS X? If Apple would only make their Java strategy clear, it might help the community figure out if that’s worth doing or not…

I can live with delayed releases, but it makes planning development a bit more difficult when you’re playing guessing games. A little more certainty would be nice.

OK, JavaFX Script is pretty cool (the platform is still boring though)

Tuesday, May 22nd, 2007

Despite my last post, I’m not actually a raving anti JavaFX maniac - the script language itself is really pretty cool. I’ve been following what would become JavaFX script since when it was called F3, and have been impressed by what it can do. Both in terms of the language syntax, and the power it gives you in certain areas.

It is very Swing friendly, and the technically, the current version provides a lot of functionality to make life easier building Swing apps. Which kinda reinforces to me that that the JavaFX as an RIA *platform* reeks of “me too!” from Sun’s marketing department in response to Flex and Silverlight.

JavaFX’s homepage will tell you that “JavaFX Script is a highly productive scripting language for content developers to create rich media and interactive content” - which I don’t quite follow. Cause it’s Swing. And while Swing is really good at regular GUIs (once you get your head around the massive API and the traps for new players), it’s got pretty weak support for “rich media and interactive content” (whatever that means) unless you are someone like Romain Guy and have time and talent to come up with a bunch of cool hacks and work around more than a few limitations with the technology.

While I’m dubious of the potential of the platform, I think the scripting language itself is one of the most interesting things to happen around Swing in a long time. It comes about as close as anything to the dream framework I talked about in JRuby Can Save Swing. It’s a pity that Sun didn’t push it in the desktop app direction, but I guess straight desktop apps just aren’t that sexy at the moment…

Anyway, here’s a quick round up of some the “kick ass” bits in JavaFX Script that caught my attention. The JavaFX Script Programming Language contains details on most of the core concepts. It’s not 100% complete, as there are a few other tidbits in the demos and the tutorial examples that show other features.

Calling Java Objects

OK, this one is kinda a no brainer. If it didn’t do this there would be trouble. I’m mentioning it just because it means you’ve got a lot of existing Java libraries you can hook in without much hassle. Scripting in the JVM is the other big buzz concept these days (and with good cause).

Cardinality Operators On Variables

When declaring a variable, you can add the following operators:

  • ? - optional. may be null (not sure if things that don’t have ? are non-nullable or not?)
  • + - one or more
  • * - zero or more

By themselves these are just another way of declaring arrays, but they tie in nicely with…

Inverse Attributes

Sure, JavaFX Script has your standard OO structure with classes and attributes that everyone knows and loves. The cool part is that you can define bi-directional inverse relationships. The effect is that when the instance on one end of the link is updated, the other end is updated in turn - kind of like cascading foreign keys. This example is the example given on the reference page:

class Person {
    attribute name: String;
    attribute parent: Person inverse Person.children;
    attribute children: Person* inverse Person.parent;
    function getFamilyIncome(): Number;
    function getNumberOfChildren(): Number;
    operation marry(spouse: Person);
}

The idea is that when a child is added to a parent, the parent value is automagically set. When a child’s parent is changed (in some strange circumstance…), the child is automagically added to the list of children on the parent object.

Array Manipulation

There is some nice syntax for working with arrays of objects as well. It all feels very SQLish. You can insert like SQL with insert myFoo first into barArray to insert in the first position, or insert myFoo after barArray[.=='foo'] to insert myFoo after whatever item in the array has the value of ‘foo’.

Or you can delete like SQL with delete barArray[.=='foo'] to remove the item with the value of ‘foo’ from the array. (The inverse attribute magic hooks in with these apparently)

You can even select like SQL (or like functional list comprehensions) with select name from album in albums where artist == "Nine Inch Nails" (there is a similar construct with foreach as well).

Pure Functions

Not really something you couldn’t do in plain old Java if you wanted to (except without the side effect guarantee), but it’s interesting that pure functions are supported as well. A pure function just has variable declarations and a return statement - which makes sure that pure functions don’t have any nasty side effects, and can be used in a functional programming style. Don’t worry, there are still regular procedures in there as well, which are called “operations” instead.

Incremental and Lazy Evaluation

This is a really nice touch, and will be one of the things that makes Swing a pleasure to work with. The bind operator will cause one variable to be “bound” to the other. When the value of the original is changed, the bound variable is automatically updated with the new value. This makes binding GUI views and models together super easy. Here’s some more code from the tutorials page which shows it off:

class HelloWorldModel {
    attribute saying: String;
}

var model = HelloWorldModel {
    saying: "Hello World"
};

var win = Frame {
    title: "Hello World JavaFX"
    width: 200

    content: Label {
        text: bind model.saying
    }
    visible: true
};

What this means is that whenever the value of saying in the model instance changes, the GUI Label is automagically updated - no need for messy listener glue code.

Now it gets even cooler. You can even bind strings that contain embedded expressions - similiar to using the "Hello, I'm #{name}" syntax in Ruby. When the value of a variable in a bound string changes, the variable it is bound to changes as well:

class HelloWorldModel {
    attribute saying: String;
}

var model = HelloWorldModel {
    saying: "Hello World"
};

var win = Frame {
    title: bind "{model.saying} JavaFX"
    width: 200
    content: TextField {
        value: bind model.saying
    }
    visible: true
};

And whenever the value of model.saying changes, the title is automagically updated!

Triggers

Related to bind (at least for Swing), is the use of triggers. When a value is changed on a JavaFX script GUI widget, a trigger is fired to set the text etc on the underlying Swing component. There are no custom setters or getters in JavaFX Script, but you can define custom behaviour using triggers. These are pretty similar to a database trigger. It’s really just some code that gets executed whenever a variable on a class instance is changed

Swing Event Dispatch Thread Support

As every Swing developer gets beaten into them DO NOT MESS WITH THE EVENT DISPATCH THREAD. For the non Swing readers, the Event Dispatch Thread (or EDT for short) handles all user input and rendering in a separate thread to the main app thread. In particular, it’s considered bad form to execute long running tasks on it (users have to wait a long time for response to their action and the GUI appears locked). And it’s also bad to update the GUI directly from a thread other than the EDT (Swing components aren’t thread safe).

This is a pain in regular Swing. There are a few frameworks for handling background operations (SwingWorker etc), and you can use the helper methods in SwingUtilities to safely interact with the EDT from other threads. But it means constructing awkward Runnable instances, usually as verbose anonymous inner classes, and passing them around.

JavaFX Script has some nice syntax sugar to take care of this. The do block allows you to execute a block of code asynchronously in another thread to the EDT (avoiding GUI lock up).

import java.lang.StringBuffer;
// in the AWT EDT
var input = getInput();
var calcResult = new StringBuffer();

do {
    // now in a background thread
    calcResult.append(doHeavyCalculationWithInput(input));
}
// now back in the EDT
System.out.println("result = {calcResult}");

This will cause the heavy calcuation to be done in a separate thread, while the EDT can carry on rendering and accepting user input (actually that’s not quite true as there is a hack with the EventQueue involved - but close enough). There are some gotchas with it though, so it would pay to read up on how it works first.

The other piece of this puzzle is the do later block which is executed in a piece of code running in a separate thread to update the GUI in a threadsafe manner. The idea is that your background thread goes off and does work, then when it is ready to display the results, it executes some code in a do later block to safely populate it to the GUI.

Conclusion

All up, there is some interesting stuff in JavaFX Script. I’ll have to have a play with it some more as it develops. Although I still don’t get the marketing blitz, the ease it should add to Swing development will be a welcome addition.

There is even a webstart sandbox app that lets you play around with the language and instantly see the results. Well worth checking out.

Flex, Silverlight, JavaFX - Who cares?

Tuesday, May 15th, 2007

It seems every Blue Chip and his dog is announcing a post Web2.0 RIA development tool these days. Adobe has Flex (aka Flash), Microsoft has Silverlight (aka ActiveX), and Sun announced JavaFX at JavaOne last week (aka Java applets). Now even Firefox is making noise about how Firefox will have features designed to go head-to-head with Flash and Silverlight! (I had hoped browser builders had learnt their lessons about proprietary browser tech in Browser War I…)

To me, this just seems like a bunch of old ideas repackaged with new Web2.0 marketing spin. It’s difficult to find developers genuinely excited about all this. Most of the noise seems to be coming from the big companies themselves.

Browser plugins have been dead for a while now. Java applets were never really that good to begin with and died shortly after birth. ActiveX kinda faded away due to security problems and cross-browser incompatibilities. Flash is still around, but really only used for (annoying) movie trailer sites, obnoxious web ads, and YouTube. It’s surprising that these ideas are being dredged up again and touted as the Next Big Thing.

It will be interesting to see where these platforms go. My guess is that they’ll fade into irrelevance before long due to developer apathy (users hate plugins as well, but thats another post). The main warning sign is that most of the noise out there at the moment isn’t from excited bloggers writing "Check out this cool Foobar app that I wrote in Silverlight/Flex/JavaFX!". No. Mostly the blogosphere is talking about press releases with an occasional overview of the technologies at a high level. No killer apps (or even mildly dangerous apps), no new possibilities that weren’t there before. Just promises of more of the same, except a bit easier and whizzier, and with video content (as if the only thing stopping every 2nd developer launching the next youtube was the current technology…). All done with a corporate designed feel and colour scheme. There just isn’t the grassroots enthusiasm there. That has to be grown organically. Not built by a marketing team.

These platforms are all trying to emulate and replace Ajax. The current usage of Ajax wasn’t engineered. It almost happened by accident through a combination of new uses of existing tech, new ideas, and realisation of new needs. There was no big bang product release, or big marketing campaign, or corporate backing. Just a grassroots momentum that built on its own due to developers seeing value in the technology and users enjoying the results. It helped that the mum and dad users didn’t have to install any additional plugins to use gmail or youtube as well.

Realistically, I think Ajax will be around for a while. It’s just that it’ll get easier to build as new supporting technologies are developed. The tech to watch are the ones that have a slow rumbling build up, then exponentially grow to a roar due to the passionate developers actually getting real value out of them. Look where Rails, Ruby and dynamic languages were a couple of years ago, and you’d find a few fanatical supporters that were passionate about it just because they could see the value. Look where Erlang and other functional languages are now and you see the same thing. They are the ones to watch. The technologies with the slow groundswell of support rather than the hollow big bang spin fest.

Life as a travel review groupie

Tuesday, May 15th, 2007

Not really coding related, but kinda cool (for me anyway).

I recently went on a holiday to Cairns in Far North Queensland, Australia. One of the friends I went with works as a journalist, and wrote up a travel review of the whole trip at Yahoo!Xtra.

‘And we’ve got water too,’ a helpful local filled in for the benefit of our two travelling companions from Melbourne, a city they both love, but described balefully as ‘brown’.

Always wondered what it would be like to go on a travel reviewer’s holiday - Its just the same as a regular one I guess.

Make The Right Way Of Doing Software Development The Path Of Least Resistance

Friday, May 11th, 2007

Imagine you’re standing in the middle of the countryside. You’ve got a place to be which is several kilometers away. How do you get there? You’ll probably just take the quickest, most easy route. It’s not necessarily the most direct route (that might go through a swamp or up the side of a mountain), but it’s the route with the path of least resistance.

The path of least resistance originally refers to electrons flowing though a circuit - the amount of current at any point in the circuit is inversely related to the amount of electrical resistance that the path at that point in the circuit has. It’s the same thing when you’re walking out in the country. If a given route is easy, you’re more likely to go that way to get to your destination. You’re less likely to go through obstacles (unless you’re into parkour or mountain biking…)

Think of the kodos and crocolisks

Now say that the direct route marches right through the middle of the endangered Giant Kodo habitat grounds, and then through the rare Crocolisk breeding grounds (both of which have been brought to the brink of extinction by over-zealous gold farming). The local environmental groups decide to do something about these rawblockers tramping through. The Kodo protection group constructs a big fence, while the the Crocolisk preservation association has built a paved track around the edge that actually ends up being quicker (but you can still go through if you want).

What is your new path going to look like? You’ll still take the easiest route. It’s just that it’s a different route now. The path of least resistance now involves having to detour around the Kodo’s, but you’ve chosen to take the new Crocolisk bypass track - because it’s quicker. The distinction is important. It’s all about the path of least resistance, and how it can be manipulated to achieve a result in the desired manner: either by making the undesirable paths harder; or by making the desirable path easier.

So what does this have to do with coding?

Exactly the same thing applies when developing software. There are dozens of ways to accomplish a given programming task. Developers are lazy, and will generally choose the solution that fits the constraints with the least amount of work. “Work” and “Constraints” are incredibly subjective terms, so it’s worth discussing them.

Work

“Work” is the measure of how much effort is expended. How hard is it, how long does it take. Some examples:

  • Time spent coding = effort (with some exceptions for doing heavy geeking)
  • Testing, documentation = effort
  • Doing tedious boilerplate code = extra effort
  • Using heavy syntax that requires frequent use of thick documentation = extra effort
  • 5 minute deploy and test cycle = extra effort
  • Interfacing with a buggy, badly documented external systems = extra extra effort

Constraints

“Constraints” is everything that limits the set of solutions a developer will consider. This includes obvious ones (like the actual software requirements), but also less tangible subconscious constraints. Some examples:

  • The client’s requirements = constraint
  • Personal pride in your work = constraint
  • Desire for respect from peers = constraint
  • Corporate development process = constraint
  • Project deadline = constraint

When you think about it, the constraints are really just a multiplier that affects the amount of effort. There may be a constraint that says “This project will be developed in language Foo”. Now you could go ahead and develop it in language Bar, but you have a lot of work on your hands explaining why you did that, and potentially redoing it all in the specified language - the effort to develop in language Bar has made it too costly to be considered an option. The path of least resistance is just to go with the flow and develop in the prescribed language.

Tweaking the path of least resistance to get what you want

Work and constraints apply at the micro-level of a single developer or a small team. They may end up optimizing on a local-minima, and be using an approach that has an overall negative aspect (such as copy/paste coding, or hard coding configuration data). If you’re in charge of a bunch of programmers, what’s the way to handle this? (assuming you can spot it - which is a whole other problem…)

Like with the Kodos and the Crockolisks, you can tweak the path of least resistance in a couple of ways:

Adding extra constraints

The most obvious way is to put extra constraints in that make it harder to do the wrong thing. This is the usual knee-jerk reaction to solve a perceived problem. “The developers are not using best practice! Lets add an extra layer of process and make 3 layers of management sign off another TPS form so that they are forced to do things properly!”. The path of least resistance is now to jump through the process hoop, and not do whatever was wrong before. This has a double whammy effect on the poor developers: They have to use a harder solution that doesn’t have the negative side effects (which is partly good - they aren’t trampling Kodos). But it adds even more process work on top the heavier best practice approach that was unattractive before (which is bad for obvious reasons).

Making best practice easier

The other option is to make the desired path more attractive. When you look at the root cause for developers not doing things properly, it could be that the key APIs on a project are heavy-weight and difficult to use. The solution may be to refactor these to make them easier to use. This is win-win. The developers are now more productive; are doing things properly; and don’t have to waste time with excess process (the problem has been reduced, so the process to fix it isn’t required).

This is similar to the carrot and stick approach, but is subtly different. Carrot and stick rewards/punishes various behavior to get the desired result. Thinking of a process in terms of the path of least resistance means changing the process itself so that the desired behavior is the easiest behavior.

Agile development in general, and Ruby on Rails in particular use exactly this approach to encourage developers to use best practice. When developing a Rails app, it is incredibly easy to use good practices such as proper project structure/test driven development/separation of concerns/DRY etc. Contrast this with J2EE - which has a multitude of ways for producing a mess, with a smaller more difficult set of approaches for producing a good clean structure. It’s no surprise that a lot more process is required to keep a J2EE project on track compared with a Rails project.

This is what I was hinting at a while back in JRuby can save Swing. Swing is a great API that gives you a lot of power. It’s just that the path of least resistance for building Swing apps is not pretty: autonomous views with tightly coupled, inflexible model and view code. A properly architected Swing app can be a thing of beauty and can elegantly grow and evolve as required. The solution I was talking about would provide a new Railsesque API layer in JRuby that would encourage developers to properly structure their Swing app using best practices.

Shine coverage of JavaOne

Thursday, May 10th, 2007

Shine Technologies (my workplace) has sent a couple of international jet setters over to San Francisco for this year’s JavaOne conference.

Mark Johnson and Ben Teese have been writing about their experiences on Shine’s blog. Reports on various presentations and the keynote are covered.

Meanwhile I’ve been sent to lovely Tasmania. Which is kind of overseas… well I mean you fly over the sea to get here from mainland Australia. Anyway, the beer is better here than on the mainland and the cooler climate is more suited to my kiwi body temperature.

Ruby multiple assignment to create unit test data

Wednesday, May 2nd, 2007

One of the tedious parts of writing unit tests is populating varying test data. Often you can wrap it all up into an array and iterate over it, other times you’re more interested in the individual objects and their interactions.

It’s not hard, but it takes up a few lines initializing each one separately. Less typing is better! Luckily, you can use Ruby’s multiple assignment operator to map all the objects you need in one hit to make your life easier:

def test_exam_result
  a,b,c,d,e,f = (’A‘..’F‘).map{|v| MyObject.new(v)}

  assert stuff(a,b,c)
  assert other_stuff(c,b,f)
  assert d_hates_a(d,a)
end