Archive for the 'Programming' Category

JavaPolis Going Nuclear

Just when I was about to drive off to Antwerp for this year’s JavaPolis, I learned that a fire has started in Antwerp’s nuclear plant ‘Doel’. Apparently the fire is located in a side building and there’s no immediate danger to the public. Which is exactly what I would say to prevent complete chaos from breaking out…

2007-12-11. No responses.

Java Closure Examples

One thing I miss in the current BGGA proposal for closures in Java 7, is a good set of examples. There are some examples, but they don’t cover most situations. Also I feel that more examples might better show the advantages of having closures in Java. Of course, as long as the Java compiler has not been patched to work with closures, this remains “swimming on dry land” (as we say in Holland). Syntax errors will no doubt be abundant, and everything might change with the next version of the proposal. I hope this will still be useful to people wondering why there should be closures in Java in the first place. This is why: it makes your code cleaner and leaner.

So here goes, starting with some simple examples. Each example consists of the closure method usage (which will probably be used most) and the closure method definition (which will mostly be done by library developers).

Select objects from collection

This is an example of how the CollectionUtils utility methods could be rewritten using closures.

public Collection<Book> getPublishedBooks(Collection<Book> books) {
    return select(books, {Book book =>
        book.isPublished()
    });
}

/**
 * Returns the T objects from the source collection for which the
 * given predicate returns true.
 *
 * @param source
 *            a collection of T objects, not null
 * @param predicate
 *            returns true for a given T object that should be
 *            included in the result collection
 * @return a collection of T objects for which the predicate
 *         returns true
 */
public static <T> Collection<T> select(Collection<T> source,
        {T=>Boolean} predicate) {
    Collection<T> result = new ArrayList<T>();
    for (T o : source) {
        if (predicate.invoke(o)) {
            result.add(o);
        }
    }
    return result;
}

Continue Reading »

2007-02-05. 17 responses.

Test Your Ruby Skills On JavaBlackBelt.com

JavaBlackBelt is a fast growing community whose members take tests to assess their skills in various Java-related topics. The tests themselves are created also by the site’s members. A small number of Ruby enthusiasts is currently working to add a Ruby exam to this Java-oriented site. I interviewed Mr. John Rizzo, one of JavaBlackBelt’s founders, and asked him what JavaBlackBelt has to offer Java and Ruby developers.

Danny: Why do we need JavaBlackBelt if we already have Sun’s Java certificates?

John Rizzo, co-founder of JavaBlackBeltJohn: We felt that, in the real world, with real teams and real projects, we have no way to assess, in an objective way, Java developers. Java requires so many things to learn. Sun is responsible for many Java apis, like JMS, Java2D, Swing, JDBC, servlet, EJB and so on. But their exam covers only a very small part of that. For example, the Sun Certified Java Programmer (SCJP) is a coverage of a small part of Java SE; JDBC, simple database access, is not even in it. And there are so many other tools and apis that are covered by other groups: Jakarta, Eclipse, jBoss. Their core business is developing their framework, not doing certifications. So there is nothing for this. If you see what a Java developer has to learn the first six months, or the first one or two years, to be productive in a project… All these technologies, and certification covers a very small part, maybe less than 10%. This is the first reason.

The other reason is that when you have three years of experience as a Java developer, and you’d like to do the first Sun certification (SCJP), you still need to study for a few days before you can take the test. Is that normal? You are an experienced developer, and you need to study, before Sun recognizes your skills. That’s why the exams on JavaBlackBelt are made keeping in mind that the candidates have all the resources available. Books, Eclipse, Google, whatever. They can search the web, search the Java apis, they can try things out in Eclipse. They’re only limited by time. They don’t have to remember things by heart. But the exams are hard, even with that. It depends on the exams, we also have basic exams, to help the beginners and to encourage the beginner to learn. Like Ruby Basic for example. And then we have more advanced exams; not just one big certification with a lot of questions.
Continue Reading »

2007-01-29. No responses.

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.

« Prev - Next »