Archive for the 'Java' Category

Swinging With Swiby

After yet another inspiring presentation by Romain Guy at last year’s JavaPolis, I’ve taken more interest in programming Swing. I programmed desktop applications for many years, using mostly Delphi. Now, after some years of web application development, discovering Swing is like finding back a long-lost friend. Why oh why did we ever turn our backs on desktop programming and open this Pandora’s box of browser incompatibilities, stylesheet hacking, a multitude of web frameworks, html files full of JavaScript, JSP files full of scriptlets, back-button-workarounds etcetera etcetera?[1] Fortunately for me, after about ten years of existence, Swing finally has a decent GUI builder as well: Matisse–even if I have to endure NetBeans to use it. At the moment, I’m working on a Swing-based variant of Picasa‘s auto-collage function (which is a nice idea but only has limited functionality).

You will probably know that Swing GUIs can be programmed as well as designed with a GUI builder. That is generally not a very pleasant activity: the code is verbose and you don’t see what you get right away. Following the ancient principle of “use the best programming language for the job, and if there isn’t one, invent a new language”, Chris Oliver developed F3, a Java-based declarative language for GUI development. In other words, a fine example of a Domain Specific Language. So maybe it was only a matter of time before someone took Ruby (great for implementing DSLs), JRuby and F3, connected the dots, and created an Ruby implementation of F3 for the Java platform. That someone is Jean Lazarou, and he named his creation Swiby. Swiby looks something like this:

require 'swiby'

class HelloWorldModel
  attr_accessor :saying
end

model = HelloWorldModel.new
model.saying = "Hello World"

Frame {
  title "Hello World F3"
  width 200
  content {
    Label {
      text bind(model, :saying)
    }
  }
  visible true
}

The question remains what you would use this for. For designing GUIs, I would still want to use a GUI builder like Matisse rather than having to code everything myself. Maybe the GUI builder could be made to generate F3/Swiby instead of spitting out endless lines of badly formatted Java gibberish. Maybe it could be made to work with a Ruby GUI library, for fast prototyping. Or maybe the Swiby code could even be used to generate… a web application?

 

[1] I’m not serious here, of course. I really love the browser and everything that comes with it.

2007-01-24. One response.

Proper Properties

In the great Java property debate, a lot of rather exotic ideas have been put forward. Using a new ‘property’ keyword; using an arrow (->) or at-sign (.@) or even a pound-sign to include null-safe access.[1] Me, I don’t get it. Sure, getters and setters make for lines and lines of repetitive code and they’re annoying to browse through. But at least they don’t get in the way when I’m coding, like the lack of closures does–to name just one thing.

So my contribution to the debate will be a conservative one, even if it is inspired by Ruby. It will not conflict with existing code or syntax. It will not use new keywords or exotic ascii characters. It will not use annotations to generate code (but it will use annotations). It will not include null-safe access. It will not get rid of getters and setters. So what will it do?

In a Ruby class, fields can be specified using one of three methods, like this:

class Person
  attr_accessor :lastname
  attr_reader :firstname
  attr_writer :age
end

After instantiating an object of this class, we can access the properties using just their names, like this:

person = Person.new
person.lastname = "Doe"
print person.firstname
person.age = 44

Even though it looks as if you’re directly using the fields, these are actually method calls. That’s right, Ruby allows you to skip parentheses on method calls, so you’re really doing this:

person.lastname=("Doe")
print person.firstname()

So where did these methods come from? They’re dynamically inserted into the class definition at runtime by the attr_accessor, attr_reader and attr_writer methods. Internally, the class can reference its fields as self.lastname. That’s how Ruby discriminates between field and corresponding method. Need a custom getter or setter? You can always define the generated method explicitly, in which case it will not be generated for you.

My Properties Proposal For Java

So how can all this revolutionary stuff lead to a conservative proposal for Java properties? As Java is not dynamic, it cannot insert methods at runtime. So how about we let the compiler insert them at compile time, in the compiled class? All you have to do yourself is declare the field–and by default, the compiler will generate a getter and setter method. How would that work out?

It will not conflict with existing code. If you already have getters and setters in your class, they will not be generated for you. I would suggest adding a compiler option to enable the generation. If you do not use the option, you do not get the generated methods. So existing code will compile and result in the same classes as they did before. Only if you do use the option, you get the new behaviour.

It will use annotations–but not to generate code. Because the code will be generated anyway. But you could use annotations to parameterize the generation. We could have an annotation to generate just a getter or just a setter. There could also be an annotation to toggle special behaviour in the methods (fire an event?). And how about an class-level annotation to turn generation on or off for all fields in that class?

It will not use new keywords or exotic ascii characters. It will not get rid of getters and setters. Getters and setters will still be there–you just won’t have to write them yourself anymore, or have your IDE insert them, or have to browse through them. Sure, you don’t get to use that cool new arrow sign. All the more reason to support the closure proposal, which has an even cooler fat arrow sign.

It will not include null-safe access. Of course it won’t. What did you think, that the compiler would do everything for you?

And now for the obligatory fantasy code sample:

public class Person {

    // Will generate getter and setter:
    private String lastname;

    // Will generate getter:
    @FieldReader protected String firstname;

    // Will generate setter:
    @FieldWriter public Integer age;

    public static void main(String args[]) {
        Person p = new Person();
        // Use the generated methods:
        p.setLastname("Doe");
        p.getLastname();
        p.getFirstname();
        p.setAge(44);
    }

}

@FieldAccess(access=NO_ACCESS)
public class Address {

    // Will not generate anything because of class-level annotation:
    private String street;

}

29-01-07 UPDATE: I have put this proposal on javap.info.

 

[1] Am I the only one who dislikes this language-design-by-ascii?

— “We need a new language feature!”

— “O don’t worry, we’ve got all these weird-looking characters that we can still use. How about the €-sign? It looks like an ‘e’, maybe we can use it to check if a collection is empty?”

2007-01-23. 6 responses.

JavaPolis 2006: The Day After

Five days after my nightly arrival in beautiful Antwerpen, I drove back over those same dreary roads to Holland, to my home. Five days that have flown by. I’ve been completely submerged in mixture of Java and a little Ruby. Everything I heard about, everything I spoke about, even dreamt about, was Java. I’ve got so many new ideas, so many things I’m eager to check out or try out:

Many thanks go to Stephan Janssen and the rest of the JavaPolis team for organizing this superb event! I’ll be back next year.

2006-12-16. No responses.

JavaPolis day 4, More on Closures

Late Thursday afternoon, in a packed room 8 of the JavaPolis venue, Neal Gafter presented his plans for adding closures to Java. He had a very well built up argumentation for why we need closures in Java. Not the usual story about the visitor pattern and putting responsibility in the object where it belongs (e.g. iterating should be done by the collection, not by the code that uses the collection). Neal’s argument was all about control abstraction. As it is right now, if you want to enclose some code–for instance, to enclose it with start/end transaction code, or with code to open and close a file that you’re using in the enclosed code–you can do that by creating an anonymous inner class containing the code, and sending that off to the enclosing code. Something like this:

  openFile(file, new Executor() {
    public void run(Object o) throws Exception {
      Reader r = (Reader) o;
      r.read(...);
    }
  });

where openFile will look something like this:

  public static void openFile(File f, Executor e) throws Exception {
    Reader r = new FileReader(f);
    try {
      e.run(r);
    } finally {
      r.close();
    }
  }

No problem here–until you try to ‘communicate’ with the anonymous inner class. Say you want to set some boolean depending on the contents of the file you’re reading. You can’t–that boolean has to be declared final for it to be visible inside the inner class. And this is just one of the problems you may encounter, like when you want to throw an exception from the inner class. You can work around all of those problems by refactoring the enclosed code. But that’s exactly the point Neal was making: you shouldn’t have to change your code.

In short, the proposal he wrote (together with Gilad Bracha, James Gosling and Peter von der Ahé) would make it possible to write:

  openFile(Reader r: file) {
    r.read(...);
  }

This looks nice enough; until you see the code that makes this possible. Unfortunately, in order to optimally fit everything into the existing language structures, a monstrous method declaration involving lots of ugly generics is needed.

Then in the evening, Neal did a small scale BOF session on the same subject, going into more detail. We discussed things like, what arguments exist against adding closures, and also the alternative proposal for which Neal had little praise. If only all JavaPolis sessions could be like this: an audience of 15 instead of 500, a small room, every opportunity to ask questions directly and discuss them in detail.

The proposal can be found at http://javac.info.

2006-12-15. One response.

JavaPolis: Closing Already

In the afternoon I attended a session about Phobos. Phobos is a web application framework that uses server-side scripting–JavaScript at first, but they’re already working on support for other languages like JRuby. Phobos’ programming model is less prescriptive than that of Rails, but familiar concepts can be recognized, like a fixed directory structure and a user-friendly url mapping system. There’s tight integration with Dojo and jMaki to generate pretty Ajax-rich scaffolds. Phobos also has an administration console, where you can inspect your deployed application (e.g. mapping rules and deployed scripts)–something that might be useful to Rails as well.

By now I am wondering who has the time to go and use all the stuff that I’ve seen over the last days. What Walhalla-like project will use even three of all those new libraries, frameworks and JSRs that have been presented? For me, after JavaPolis, it’s back to Java 1.4.2, Struts and Maven 1.2. Things like EJB3, JSF, GlassFish, Java 6 or even 5–it’s all purely restricted to hobby projects at home or at best to projects for interns that I’m coaching (they don’t know how lucky they are). Let alone Ruby and Rails. Like walking around in the chocolate factory, knowing you’ll be eating sprouts again tomorrow…

And now I’m off to (hopefully) another JavaPolis highlight: Neal Gafter on closures for Java. For some reason, a more detailed session of his on the subject has been scheduled tonight, at the same time that the JavaPolis movie (Casino Royale) starts. Doesn’t Neal like James? Or is it an intricate test to see who’s fanatic enough about Java to miss the movie? We’ll see…

2006-12-14. No responses.

Revenge of the Groovy Guys

Okay, okay, I’ll humbly admit I was wrong. A little bit. About ehm… that Groovy thing. An inspiring session by … about the Grails framework made me see things from a different perspective. There’s actually some quite nice features in Grails that could well be of use in Rails (or in some cases, Rails on JRuby).

For example, I’ve been looking for some time now for a system that would allow custom html tags in Rails’ rhtml files. The idea is to allow for all sorts of html tags, for example

  <r:for_each list="some_list" var="item">
    <li><%= @item %></li>
  </r:for_each>

This would then trigger a method named for_each (e.g. in a app/helpers/application_tags class) which could process the passed inner html block in any way you want (in this example, probably looping through some_list). Even though Ruby code in rhtml is usually not hard to read, it would still clean things up a bit and get rid of some duplicate code.

In short, it turns out that Grails already has this. Grails also has deployment to war (which is still experimental in JRuby, it’s the first thing I’ll try out once I’m back home from Belgium). And because Grails is built on top of Spring and Hibernate (amongst others), it’s easy to script-prototype your model classes that could be Hibernate-mapped or EJB3s. To be honest, that one isn’t any more difficult in JRuby if you see how easy it is to call any EJB.

Another interesting Groovy/Grails language construct I saw:

Book.get(params.id)?.true

The interesting part here is the question mark operator. This will (apparently) check if get() returns null, and if so, prohibit an error being thrown. There was an interesting discussion about this some time ago on rubyenrails.nl (in Dutch; I’ll post the link when I’m home), looking for ways to do this in Ruby.

All in all, I’m still not comfortable with the Groovy syntax (too many curly braces and arrows; and I’m missing semicolons at the end-of-lines–it’s not Ruby after all!) but there’s definitely things to learn and shamelessly steal from those Groovy and Grails guys.

2006-12-14. 6 responses.

JavaPolis day 4, The Monkey in the Details

On Thursday, Marc Fleury finally delivers his keynote on the open source business. I get distracted by circumstantial details like Fleury’s ridiculous “Public Enemy #1” costume (reminds me of Steve Ballmer’s stupid monkey dance) and An running around him with her camera like a groupie, trying to catch Marc’s best angle (what lens is she using? why does she never use a flash?). Oh man, Marc is actually dancing now. See you soon on Youtube…

(I can imagine you’re getting tired of my supposedly witty blog post titles. Don’t hold back, let me know, leave a comment!)

UPDATE


Marc Fleury at the mike for his JavaPolis keynote

2006-12-14. No responses.

JavaPolis day 3 continuated

Wednesday afternoon, JavaPolis really got into gear for me. I saw short ‘quicky’ sessions on Unitils (don’t like the name but some of the features (assertion through reflection!) could be very useful to me, as I’m writing tests on a daily basis) and Strecks (Struts extensions that can easily be used in an existing Struts environment–all the more pity it requires Java 5; won’t most existing Struts-based applications still be using Java 1.4, like the project I’m on right now?).

Next, I did a lab on NetBeans and Matisse, the NetBeans gui design tool. It really brought back memories of my Delphi days. I must say, NetBeans feels slick and fast and stable. Add to that the Ruby support that Tor Norbye is working on, and this might well become my next IDE of choice. We got a small sample of that in Charles’ and Tom’s conference session on JRuby, which was next. Charles showed things like usage highlighting and local rename. It might not be spectacular for a crowd of Java-with-(probably mostly)-Eclipse coders, but you’ve gotta start somewhere! (But on the other hand, Eclipse so often gets it ‘just right’–like in 3.3, the local rename got enhanced to operate locally within inner loops; such a small thing but something that happens often enough).

By the way, if the JavaPolis team is listening: those labs could do with some more publicity. Only four people out of 2800+ showed up. Maybe because the labs are somewhere in the back of the conference guide; I just found out myself a few minutes before it started. Maybe because the location is a very dark corner of MetroPolis. Worse, there was a loudspeaker directly above the lab location, blurting out advertising for MetroPolis at a very high volume (every 2 minutes Eddy Murphy shouting “Show me the candy!”, argh!).

I liked Brian Goetz’ session last year, and this year he was just as enthusiastic, showing us the reality about some Java performance myths. I know now that object allocation is normally not slow, and synchronization isn’t always slow either. Best myth however was “Clever code is faster code”. It turns out that, in normal situations, the best performing code is cleanly written code, following standard guidelines. Java is not a one-liner language.

It had already been a long day when we sat down for Geert Bevin’s session on continuations–in Java. This is definitely a fascinating concept; for using it in web applications however, it just might be too different from the way we ‘normally’ do things. It requires nothing less then a paradigm shift in web app development. More info on continuations can be found on the RIFE site.

2006-12-13. No responses.

JavaPolis day 3, Keynotes and Keynots

Another unexpected program change at JavaPolis brought us Oracle’s Omar Tazi (director of SOA evangelism and Chief open source evangelist) instead of Marc Fleury in Wednesday’s keynote session.

Unfortunately, a school example of how not to do a presentation. We got an hour-long talk of Omar clicking away on his laptop, showing All-New Oracle product after product, one enterprisey acronym after the other, all the while complaining about how little time he had left for his presentation (actually counting down the minutes). At the same time it’s sad to see the Web 2.0 revolution being enterprisified by companies like Oracle–and in name only, because the JSF+Ajax screens filled with components stacked from top to bottom, are all but what Web 2.0 has been about. Then again, knowing Oracle, I’ve probably been watching a demo of Web 2.0.13.10…

The Sun keynote provided more fun, even though I had already seen most of it at this year’s NLJUG JFall session: Simon Ritter’s Sun SPOT robot cars chasing eachother, and Angela Calceido’s cyberglove directing the mouse pointer in LookingGlass. We also saw a short promotion video with Richard Stallman giving praise to Sun’s open source move (he’s getting old… I thought heroes weren’t supposed to grow old…).

But before all that, Stephan Jansen started off with the usual JavaPolis introduction. Over 2800 attendants this year from all over the world, making the venue, MetroPolis, almost too small. There have been lots of small improvements this year; more food and free wifi being the most basic ones. Too bad that the free wifi and the dns server behind it are very hard to connect to. But what’s really a shame is that the speakers aren’t provided with a guaranteed working connection; several demos had to be cancelled because of that.

After the keynote we went downhill again, with a session on Apache Tuscany by a very (very) nervous Andrew Borley, poor guy. Sheet after sheet filled to the brim with bullets and text that was being read outloud almost literally. The technology itself is really interesting from a SOA point of view (an open source implementation of Service Component Architecture and Service Data Objects, supporting components written in any language like Ruby or Java, interoperable via SOAP or REST)–but really it hardly comes across this way. I’ll visit the website instead.

2006-12-13. No responses.

JavaPolis day 2, Best of Both Sides

I’m being urged to choose sides. Colleagues say I should specialize in either frontend or backend development. I’ve never liked to commit to any specialization. Partly because I’ve always admired the renaissance ideal of the uomo universale who knows and does it all. But also because, when I started out my career, 20 years ago, jobs were a lot scarcer then nowadays, so you couldn’t be all too picky about which job you wanted to do. Specialization is nice until the market changes and you find yourself out of a job because you happened to choose the wrong side.

All this might explain why I enjoyed a full day of Swing yesterday at JavaPolis, even though my day job is now exclusively about backend domain design and coding (and I love it, I love being in the silend, cold spelonks that the domain is, where everything perfectly fits, everything is under tight control with unit tests, and the evil outside world of user interfacing is far far away).

To be honest, the alternatives didn’t appeal to me either. A session on POJO programming–who on earth can talk about plain old POJOs for three whole hours? Or what about a Spring 2 session? Never mind, I’ll read the release notes. Now Swing, that’s something you want to see live. Not that there were many flashy demos though; just a very cool mashup that allows you to map your holiday snapshots to a route you can draw yourself on a Google map. Most of the time was filled with new Java SE 6 features, tips & tricks, a useful tutorial on Java Web Start, and an interesting but theoretical presentation on humane user interfaces (by Romain Guy).

Those new SE 6 features, they’re nice enough, sure; but it made me think back to my Delphi days, about 10 years ago, when we already had things like date pickers and hyperlinkable labels. In a way, it’s really the same as with all the fancy Ajax stuff. We’re all so excited about a web page that can behave like a desktop application; but if we’re actually developing a desktop application, then why bother with web pages when we could have made life easier and used Swing instead?

2006-12-13. 3 responses.

« Prev - Next »