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.

« Prev - Next »