General musings on programming languages, and Java.

Wednesday, October 10, 2007

Why Java Needs Closures (It Already Has Them)

Some bloggers and people I've talked with think of closures in Java as something unnecessary - e.g., "why must we copy C#?". As it happens, most languages have closures, including Java.

A closure is an executable block of code that can refer to free variables from the enclosing scope. Here's an example in Java:


public void example()
{
        final double use=Math.random()*10000;

        SwingUtilities.invokeLater(new Runnable()
        {
                public void run()
                {
                        System.out.println(use);
                }
        });
}
It's not a great example of how closures are useful. The instance of that anonymous class can reference the variable 'use'. In fact, there's a leak in the implementation that gets into the language - 'use' has to be final. That doesn't stop the anonymous class from being a closure. Let's consider how life would be if Java didn't have closures:
public void example()
{
        double use=Math.random()*1000;

        class MyRunnable implements Runnable
        {
                private double use;

                public MyRunnable(double use)
                {
                        this.use=use;
                }

                public void run()
                {
                        System.out.println(use);
                }
        }

        SwingUtilities.invokeLater(new MyRunnable(use));
}
In fact, that's not far off what the first code sample gets compiled to. In Java 1.0, inner/nested/local/anonymous classes didn't exist, so you'd have to take the above MyRunnable, and put it in a separate file, but the code would be the same otherwise. If you were going to complain about Java getting closures, Java 1.1 was the time to do it!

The above two code samples work in today's Java, and some of you might even favour the second, because it's more explicit - it matches the bytecode more closely.

The way I think is that you should, at least as a thought experiment, take anything like "favour explicit code over abstract code" to an extreme, to test it out. The most explicit you can be in programming is to write assembly code, and none of us wants to do that. Let's flip it around. The most abstract you can be in programming is to write in Lisp, and none of us wants to do that. Both of those statements have holes in them, of course, there are some people who love writing assembly, and there are some who love writing in Lisp. I'm one of the latter.

As it turns out, abstraction is so prevalent in programming that most of us program in languages that are closer to Lisp than they are to assembly. C is the lowest-level programming language that I know, and even it has huge abstractions over the underlying assembly.

Java programmers are already programming on an abstraction, the Java Virtual Machine, before they even worry about syntax. It seems that we already favour abstract code over explicit code. Abstract doesn't mean imprecise, or vague, it's another way of saying "general". We can use abstractions to stop repetition.

Consider the above code samples as templates of some kind:

        final $TYPE $VAR=$VAL;

        SwingUtilities.invokeLater(new Runnable()
        {
                public void run()
                {
                        $ACTION($VAR);
                }
        });
and
        $TYPE $VAR=$VAL;

        class $BLAH implements Runnable
        {
                private $TYPE $VAR;

                public MyRunnable($TYPE $VAR)
                {
                        this.$VAR=$VAR;
                }

                public void run()
                {
                        $ACTION($VAR);
                }
        }

        SwingUtilities.invokeLater(new $BLAH($VAR));
The first template has 4 parameters, $TYPE, $VAR, $VAL, $ACTION. It mentions $VAR twice, the others once each.

The second has 5 parameters, $TYPE, $VAR, $VAL, $ACTION, $BLAH. It mentions $TYPE 3 times, $VAR 6 times, $VAL once and $ACTION once. We're always taught not to repeat ourselves in programming, and we can easily see that the second template is more repetitive than the first. A less well-known rule is to avoid unnecessary names. MyRunnable is a name that's defined once and used once - a bad sign.

Extra repetition means extra scope for errors. You might change 'use' between calling invokeLater and invokeLater actually happening - now you've got a sync problem. This is because you had to copy your variables yourself. Admittedly, thanks to the 'final' restriction, Java doesn't help much there, but at least it stops broken code from compiling.

Let's briefly return to the restriction that the local variables that anonymous classes capture must be final. Does that stop anonymous classes from being closures? Changing the values of variables is kind of an optional feature in programming languages. Mathematics seems to have managed without x++ for many years. Java's anonymous classes place some restrictions on what kind of variables are considered free, but that doesn't stop them from being closures. Haskell definitely has closures, and definitely doesn't have mutable variables.

Ok, with all that out of the way, we now know that Java has closures, and they aren't disappearing anytime soon. Let's take a moment to laugh at the blog posts (actually most of them are anonymous comments on blogs) saying that Java doesn't need closures.

There. Now let's briefly examine why Java needs better closures, by returning to our template. This time we're going to read it with boilerplate glasses:

        boilerplate double use=Math.random()*10000;
        SwingUtilities.invokeLater(boilerplate System.out.println(use));
What we'd like to do now is to make that boilerplate disappear. Scala has an interesting way of doing that:
        val use=Math.random*10000
        invokeLater(System.out.println(use))
Scala methods can have lazy parameters, that is, parameters that are not evaluated at call time, but are evaluated when the method wants to. You can use that to write your own if method, e.g.:
        myIf(Math.random<5,System.out.println("Still here"),System.exit(0))
Of course, myIf is just an interesting result, and not actually useful, but in the case of invokeLater it is useful; it gets rid of a lot of our boilerplate.

Java 7 closures let us do pretty much the same thing:

        double use=Math.random()*10000;

        SwingUtilities.invokeLater({=> System.out.println(use));
There is another syntax for the last line:
        SwingUtilities.invokeLater()
        {
                System.out.println(use);
        }
We still have a little boilerplate with both these syntaxes, but not enough to need the boilerplate glasses. Sadly, despite it being technically possible for IDEs to become boilerplate glasses, they haven't done so. Folding an anonymous class in IDEA looks like:
        new Runnable(){...}
They've folded the wrong thing. Duh. It should look more like:
        new ...{System.out.println(use);}
Some people think that Java doesn't need better closures because Java as a language is already broken in many ways. Often Scala is quoted as the next Java. I've tried Scala out - it's very impressive, and similar enough to Java to not have too many surprises. So in one sense I agree, but I also think that Java should have better closures to move the status quo of programmers up a notch. Programmers should consciously favour abstraction over boilerplate, instead of the current situation, where many use abstractions all the time but are reluctant to invent their own.

Being free of boilerplate lets you think in different ways. My post on point-free programming shows one route you could take - there are many others.

Friday, September 14, 2007

Point-free Programming in Java 7 - Beyond Closures

Here is an introduction to point-free programming, using Haskell, Scheme, Java 5 and the proposed Java 7 for examples, and a couple of ideas for how the Java 7 proposal could improve to make point-free programming more practical.

I've grown quite accustomed to programming in lambda style now, in Common Lisp, Scheme and Haskell. Here's a quick example of how that looks:

Scheme: (lambda (x y) (+ x y))
Haskell: \x y -> x+y
Java 5:

new FunctionIII()
{
    public int invoke(int x,int y)
    {
        return x+y;
    }
}
Java 7: {int x,int y => x+y} Not too bad. You could use this to fold (or reduce) across a list. To fold is to apply a function on a starting number and an element of a list, and then to apply the same function on the returned value and the next element of the list, until the end of the list. You could use this to compute the sum of all the elements of a list:

Scheme: (foldl (lambda (x y) (+ x y)) 0 (list 3 4 5 6 7))
Haskell: foldl (\x y -> x+y) 0 [3,4,5,6,7]
Java 5:

foldl(new FunctionIII()
{
    public int invoke(int x,int y)
    {
        return x+y;
    }
},0,asList(3,4,5,6,7));
Java 7: foldl({int x,int y => x+y},0,asList(3,4,5,6,7));

One point to note here is that you could, in Scheme, write this as (+ 3 4 5 6 7), because Scheme's + function takes any number of arguments, even 0 (whereupon it returns 0). So this is a contrived example using non-optimal code.

It's not idiomatic Haskell either. For a start, you can write sum [3,4,5,6,7], and avoid foldl altogether. Bear with me for a moment though. In Haskell, you can shorten \x y -> x+y to simply (+), which means 'the function called +'. In Scheme you don't even need the parentheses. +, used in a 'value position', which is anything other than the first in a list, refers to the function +, rather than calling it. So you can do:

Scheme: (foldl + 0 '(3 4 5 6 7))
Haskell: foldl (+) 0 [3,4,5,6,7]

This is the simplest example I can think of of pointfree style, which is where you remove lambda expressions but without introducing mutable variables. Here's a better example:

I want to multiply all elements of a list by 2. Here's the lambda style:

Scheme: (map (lambda (x) (* x 2)) (list 3 4 5 6 7))
Haskell: map (\x -> x*2) [3,4,5,6,7]
Java 5:

map(new FunctionII()
{
    public int invoke(int x)
    {
        return x*2;
    }
},asList(3,4,5,6,7));
Java 7: map({int x => x*2},asList(3,4,5,6,7));

But these lambda expressions don't really express my intent that well. I want to map the function 2* across the list. Haskell has a convenient syntax for this:

Haskell: map (2*) [3,4,5,6,7]

What I've done there is to specify the * function, with its first argument filled in. This works because all functions in Haskell are automatically curried. If I type this at the REPL:

:type (*)
Output: (*) :: (Num a) => a -> a -> a
This looks a bit confusing if you're not familiar with it. What it means is that (*) is a function with a type parameter, a, which in Java terms would look like <a extends Number>. It takes one parameter of type a, and returns a function that (takes one parameter of type a, and returns a value of type a). Parentheses used for disambiguation there, this turns out to be hard to write in English.
:type (2*)
Output: (2*) :: (Num t) => t -> t
That means that (2*) is a function with a type parameter, t, which is an instance of the Num typeclass (the same as 'a' in the first example). It takes one parameter of type t, and returns a value of type t.

So I can call (2*) as an ordinary function, adding a value (this is called taking a section, and is a way of partially applying a function). The following expressions all have the same output, 8:

(2*) 4
(*2) 4
(*) 2 4
((*) 2) 4
This seems like an interesting but not-so-useful result of automatic currying at first, but you can actually rewrite any lambda expression in this style. Sometimes the code will be easier to read than a lambda expression, sometimes not. Here's a more complex example:map ((+10) . (*2)) [3..6]

The . operator means function composition, like in mathematics - f(g(x)) would be written as (f . g) x. You can compose functions before you have the values to give them, so f . g has a meaning. Read ((+10) . (*2)) as: "multiply by 2 then add 10". Look ma, no variables!

Scheme doesn't have any support for this, as its procedures are not automatically curried, but you can make something similar happen:

(map (compose (plus 10) (multiply-by 2)) (list 3 4 5 6))

plus and multiply-by need defining in an odd way:

(define plus
    (lambda (x)
      (lambda (y)
        (+ x y))))
(define multiply-by (lambda (x) (lambda (y) (* x y))))

You can write a general curry procedure in Scheme, but as there's no portable way of discovering how many args a procedure takes, you have to supply the arity. Plus, some procedures are of variable arity.

(curry 2 +) would return a procedure that takes a value, and returns a procedure that takes a value and returns the sum of the two values, used like this:

(((curry 2 +) 4) 5) ;; output: 9

Java 5:

public static final FunctionIO<FunctionII> plus=new FunctionIO<FunctionII>()
{
    public FunctionII invoke(final int x)
    {
        return new FunctionII()
        {
            public int invoke(int y)
            {
                return x+y;
            }
        };
    }
};
For brevity I'll leave multiply-by out.. it's the same but with + changed to *!

Java 7:

public static final {int => {int => int}} plus={int x => {int y => x+y}};
public static final {int => {int => int}} multiplyBy={int x => {int y => x*y}};

map(compose(plus.invoke(10),multiplyBy.invoke(2)),asList(3,4,5,6));

Because both Scheme and Java make you curry explicitly, they discourage point-free programming (although it's still possible, and quite useful). I'd like to see all function types in Java 7 be automatically curried. In other words:

{int,int => int} should be the same as {int => {int => int}}.

This doesn't have to have any negative impacts at runtime, as demonstrated by Haskell's great performance.

To make it really useful, it should also be applicable to operators, so that #+ gives a {int,int => int} and #+.invoke(2) gives a {int => int}. (where #+ is a possible syntax for taking a reference to +).

Sometimes you'll want to provide the second argument rather than the first. Haskell's solution to this is a function called flip:

(flip (/)) 3 6 -- gives 2, the result of 6/3. I could use it in this possible future of Java with #/:

flip(#/).invoke(3) would return a {int => int}, that, when you pass it a number, it returns that number divided by 3. Equivalent to Haskell's (/3).

As you do more and more in point-free style, you get more and more used to it, as one would expect, and some constructs that seem unnatural at first seem normal later. I'm still a novice, but I'm having fun.

Saturday, August 25, 2007

Stop Sitting On The Type Fence

Static typing is not just about preventing simple bugs, and dynamic typing is not just about writing millions of tests that you wouldn't have to write with static typing.

Programmers of languages like Java, C#, C, C++, etc., middle-of-the-road statically typed languages with some dynamic features, have some intuitions, built up from years of experience at getting the best out of their language, but don't often stop to see what contortions their language makes them go through, or that they are limited in what their compiler tells them about their code.

They often think that rigorous static typing is about preventing bugs that a few unit tests would solve, or that dynamic typing is about writing tests that static typing would solve.

Static Typing is Not About Low-Hanging Bugs

Many years back, clever mathematicians proved that functions express types. If you have an expressive enough type system, you only need to give the input and output types for a function, and you have its implementation. Consider the identity function, written in Scheme like this:

    (lambda (x) x)
Don't worry if lambdas are unfamiliar to you. No, actually, do worry. Lambdas underpin most of computer science and certainly all of programming, even if that's not obvious. If, as I did, you gained a Computer Science degree without ever hearing about lambdas, ask for your money back, and spend it on a copy of The Structure and Interpretation of Computer Programs (SICP) for you, all your friends and family. It's also available in PDF form for no money, in case you're unsuccessful in getting your money back from your University.

Anyway, a lambda expression is analogous to an anonymous function in many languages, and even an anonymous class (with one method) in Java. The particular lambda expression above is a function that takes a value, and returns that same value.

In Haskell, the syntax isn't much different:

    \x -> x
The \ is Haskell's approximation to the Greek letter lambda, the bit before -> is the parameter list, and the bit after it is the result. Scheme doesn't care about telling you the types of things, but Haskell does. The type of \x -> x is t -> t, which means it's a function that takes a t (which can be anything) and returns a t (which is the same as the first t). All fairly obvious.

Given the above, there's only one logical implementation of t -> t, and that's \x -> x. You could make silly ones, where you store x in a local variable, and then return it later, but they're all equivalent. Or perhaps the implementation could look up the type of x, and grab something similarly-typed from a cache. All a bit silly though. Perhaps if all types in a language had a clone function, then you could provide a different implementation, but without that, or something similar,

What you can see from this is that, at least for simple functions, you only need the types to derive the implementation. Does this scale up to things like \x y -> x/y, etc.? Yes, as it happens, though you then need the concept of dependent types, which is types that depend on runtime values. They can still be checked at compile time. In other words, types and values are isomorphic to each other (isomorphic is a mathematical way of saying 'equivalent').

What does the Java version of the identity function look like? Oddly, it depends on whether you write it how Scheme works, or how Haskell works. In Scheme there are no compile time types (or you can say there is exactly one), and the closest that Java comes to that is Object:

    public static Object identity(Object x)
    {
            return x;
    }
If you write it like Haskell, then you need to make sure that the return type is the same as the input type, with no silent upcasting (to Object):
    public static <T> T identity(T x)
    {
            return x;
    }
There is quite a difference between the two pieces of code, which is particularly disturbing, because the Haskell and Scheme versions look so similar to each other. In fact, there's a project called Liskell, which gives Haskell lispy syntax. There, the two would probably be the same. This is a first hint that Java gets in the way of thinking about static typing, by making it very verbose, in particular by making untyped code look different to typed code.

Haskell is also guilty of this, partly by design, and partly because of some deficiencies in its type system. That's the reason that the side of the fence I sit on is the dynamically typed one, but I keep my eye on the static typing people, because they come up with great ideas, and secretly I'd like to be able to use their type systems on some of my code.

So static typing isn't just about making sure that you don't add two credit card numbers together, it's about expressing code as close as possibly to mathematics. Mathematicians tend to be very good at reducing problems to their smallest representations, and coming up with very general solutions, so there can be no doubt that this approach will (and already has) produced amazing results.

Haskell's type system is certainly imperfect, and so are its programmers - this is clear because of the presence of its unit testing system, QuickCheck. If the type system was perfect, and the programmers using it never took shortcuts, there would be no need to run unit tests. It would be evident by the compiler succeeding, that the code could not crash, or produce any results outside the expected range.

If you look for more and more sophisticated type systems, you will probably come across Coq at some point, which is a proof engine that can generate executable code. There you deal with logic, with set theory, all things that are the pinnacle of static typing, and which my Computer Science degree, and probably yours, did not cover.

Go there. Have a look. Even if you decide that static typing is not for you, or that you'll get by with a lesser static typing system such as Haskell's or Java's, you can learn a very general way of thinking that will apply across a lot of programming, in the same way that understanding lambdas will help you when you see C# delegates, JavaScript's anonymous functions, etc.

Dynamic Typing is Not Just About Writing Tests

Many static typing proponents, even Haskellers, have the opinion that while Lisp, Python, Ruby, JavaScript, et al, might have some nice syntax, the fact that they are devoid of static types makes them ultimately useless. You can't easily get the compiler to tell you if you try to do something stupid. For example, 3/"hello world" will be accepted by the language despite it being obvious (read: provable) that a runtime problem will occur.

Many Java programmers assume that you have to guess at the types being used in a dynamic program, or provide excessive documentation. The greater point is that what will work will work. Dynamic languages get out of your way so that you can explore a problem. Whereas in a statically typed language you have to make the solution consistent before you can try it out, you can try out an incomplete function very easily in dynamically-typed languages.

    (lambda (x)
      (if (< x 0)
          (do-this x)
          (do-that x)))
I can call the above lambda on negative numbers, even if do-that hasn't been written yet (assuming do-this has). The runtime doesn't generally complain unless it has to.

Once you have explored a problem, and you understand it, you probably have a nearly-working program, so you're pretty close to having a working one. You get no guarantees that the program will work for all possible inputs, and there isn't even a general way of restricting inputs (other than adding checks at runtime).

Dynamic programmers tend to think in the language they are using - that is, they write code while they're thinking, and test functions out to see whether they work for the cases they're interested in. If I write a function that adds two numbers together, I'm not even remotely interested in what happens if someone passes strings to it, because I'm not writing it for that use case.

This way of thinking keeps the code focused on the task in hand. If the code starts to get hard to read, or repetitive, the programmer will come up with an abstraction. E.g., beginner Java programmers often try this:

    if (x==3 || 5 || 10)
which doesn't compile, because the compiler sees 3 expressions that should all be booleans, and the 2nd and 3rd are ints instead. The programmer gets told they're wrong, and they should fix it to be:
    if (x==3 || x==5 || x==10)
That's clearly garbage, because x== is repeated. The programmer has just adopted a poorer way of thinking to suit a language, instead of adapting the language.
    if (x in (3,5,10))
would be great, as would:
    if ((3,5,10) contains x)
, or even, as valid Java:
    if (asList(3,5,10).contains(x))
Of course, this latter example is a little ugly. Translated directly to Scheme:
    (if (contains (list 3 5 10) x)
If this was used a lot, a Scheme programmer might write:
    (if (in? x 3 5 10)
A Java programmer could do that too, but they would need to know more of the language to be able to do it. Therefore, the Java programmer is 'corrected', instead of shown how to write their idiom in Java.

Because the language gets out of the way, this kind of code is easy to write. That brings about the worry that because you can write code to be as good as you like, you can also write incredibly bad code, and this is completely true.

The remarkable thing is that the language doesn't try to judge whether your code is good or bad - it just runs the code. That's great, because it lets you learn from your own mistakes, and even better, it lets you come up with things that the language designers didn't think of.

It's become quite clear in recent years that Object-Orientated Programming as Java and C++ do it is not the pinnacle of software engineering - but you can't escape Java's OO system. You can't really implement multiple dispatch for two separate codebases in one central place unless you go outside the language (e.g., reflection, bytecode weaving). If it turns out that Haskell's typeclasses aren't the best way of expressing things, you can't remove them from the language, because existing code depends on them - the compiler always needs to understand them - and probably you will still have to use them because the language's central concepts depend on them.

By the language not telling you that you're wrong, it lets you be right in ways that the language designer might not have envisaged. For example, the code snippet (+ "hello" "world") looks wrong, because + is not defined on strings. But in a language like Scheme, + is only a variable, so I can write:

    (let ((+ string-append))
      (+ "hello" "world"))
and it's no longer wrong (arguably a bit stupid though).

So how about those tests? Well, if you look at Java code:

    public Integer add(Integer a,Integer b)
    {
        return a+b;
    }
Both a and b can possibly be null, so what happens if null is passed? Er, you get a NullPointerException. Some programmers will specify that in documentation for the method, or just write that null is not allowed. The same method in Scheme would be callable with any values at all, though it would fail. That changes the attitude of calling programmers. Instead of looking at the half-hearted type signature, and seeing that null is a possible value, the programmer is more likely to look at the implementation.

In the first half of this entry, I said that types imply implementations - well, the reverse is true! Implementations imply types. You don't need a type signature to see what values can be passed to (lambda (a b) (+ a b)), you can infer the type signature from the implementation. In this case, you can pass anything to that lambda that you can pass to the primitive + procedure, whose type signature actually depends on the implementation of Scheme you're using, but it accepts at least those types in the specification.

So Scheme programmers aren't likely to write tests to see what happens if you pass credit cards to a function expecting addresses, because that's never going to be a use case. They informally restrict the inputs. They're emulating what a static type checker does, but mentally. That lets them organically approach a solution to a problem, instead of having to design it beforehand.

It's certainly true that this mental processing is error-prone, and bugs get into source code because of this. Then, many programmers are tempted to write swathes of tests, in an informal attempt to prove that their code is correct.

The bad part of this is that they aren't benefitting from the static typing camp's results now. They have a solution, but they can't use the machine to prove it. They'll end up writing the same kinds of tests over and over.

All this is why I think that, despite him talking about middle-of-the-road type checkers like Java's, Gilad Bracha was on the ball with his presentation about adding pluggable type checkers to dynamic languages. I thoroughly expect that it will be some time before a great one exists, and largely because too many people are sitting on the fence, instead of knocking it down.

If you ignore mediocre languages, there isn't a great deal of difference between how statically typed programmers think and how dynamically typed programmers think. We all like lambdas, we all like side-effect free code, we all dislike crashing programs. So the next time you see a proposal to add static typing to your favourite language, or to add some new dynamic feature to your static language (including 'get-out' clauses like Haskell's unsafePerformIO), bear in mind that you're just witnessing a step on the road to convergence.

If the next big language has a mandatory static type system, then it will either be a crap one, or Computer Science degrees will suddenly contain a lot more mathematics. That won't happen. The next big language will be crap, or dynamic.

Tuesday, August 21, 2007

Objects To Functions 1 - Stateless Classes

Before I had really heard of functional programming, I had started to notice that it made a lot of sense to make certain objects 'value objects', i.e., create them with all the data they need and then never change them, which lets you pass them around without worrying about who changes them. This sounds like low-hanging fruit, I mean, of course you can easily keep track of changes, just like C++ programmers always manage to track who frees an object.. Ah. You probably see where I'm going now. So, if I don't mutate an object, I can pass it around without thinking about the consequences. That's why it turns out to be better to share Strings rather than StringBuffers in Java. Of course, you can treat a StringBuffer as an immutable value, just by never mutating it, but as it is intended to be mutated, you generally don't share it, at least not without thinking very carefully. Let's look at a very simple stateful class:


public final class Point
{
    public double x,y;
}
I'm sure some readers will be complaining about the lack of get/set methods now - I'll happily explain why I don't use them if you ask in a comment. Others may complain about final, I'll happily explain that too. If you instantiate a Point and pass it around, some programmers will see that it's intended to be mutable, and store a copy of it (or take pains never to store it, but just use its values once), and other programmers will take the attitude of, well, if you're giving out a mutable object you'd damn well better expect it to be mutated*. The latter sounds like an unreasonable attitude, but it's why IDEA places warnings on methods that return the values of fields that hold arrays and collections. IDEA puts the onus on the class giving out the mutable object, rather than on the user of that object - it assumes that the latter programmer is the most likely one. * this latter programmer often also has the attitude that while it's ok for him to mutate the object, nobody else should! It's quite easy to make Point immutable, you can provide a constructor that sets x and y, and then make x and y final. You don't absolutely have to do this - all it really takes to stop a data structure from being modified is to stop modifying it - you don't have to put up barriers to modification to do that. Still, in Java modifying things is the norm, so it might be a good idea for now. If you get to a stage where mutation is only done with great care then you might not need the barrier.

public final class Point
{
    public final double x,y;

    public Point(double x,double y)
    {
       this.x=x;
       this.y=y;
    }
}
So, how does this relate to functions? A Point is now a function, as in mathematics. If you create a Point, it will always give you the same value for x and the same value for y. You can think about it as a function that takes the symbol x or the symbol y and always gives the same result. That is, objects can be or represent functions just as well as methods can. Math.abs represents a function, because it always gives the same output for the same input, and so does point.x. Now I can treat a Point as a long-lived value and never worry whether it will be mutated, just as I don't worry about it being garbage collected. In effect, I've taken time out of its semantics. You might be thinking that Point is crying out to be an interface, because programming to the implementation is inflexible. However, I'd like all clients of Point to be able to rely on .x and .y returning the same thing, forever, and not have to worry about different implementations doing strange things. Instead I would suggest that if you wanted a different implementation, you don't call it Point, and don't try to make it extend or implement Point. Clearly it would be of a different type, e.g., MutablePoint, or DebuggablePoint, Quaternion, etc. - and you wouldn't want to use it in places that expect a Point. There are cases that make this way of programming tricky, and solutions to each: 1. Collections. It would be pretty expensive to copy a collection instead of changing it, so in many cases you may as well change it in place, which loses you the time-independence, and stops the collection from behaving as a function. There are some concessions you could make - e.g., only allowing adds, not removes (then any successful accesses will always succeed - you won't break assumptions). For the more general case, there is one kind of collection in particular that works well as a function - a linked list. Java's LinkedList class doesn't give you access to the individual nodes of the list, which is what we need for this to work, so you'd need to write your own.

class Link<T>
{
    public final T item;
    public final Link<T> next;

    public Link(T item,Link<T> next)
    {
        this.item=item;
        this.next=next;
    }
}

Link<String> list=new Link<String>("hello",null);
If you feel the need to add to the list, you don't need to change anything, just call new Link<String>("world",list) and use that value instead from now on. Then each list retains its properties as a function - it will always return the same value if you ask it the same question. If you want to iterate over such a linked list and do something, say, finding the maximum of a Link<Integer>, you could do it like so:

public int max(Link<Integer> list)
{
    int max=Integer.MIN_VALUE;

    while (list!=null)
    {
        max=Math.max(max,list.item);
        list=list.next;
    }

    return list;
}
This works, and from the outside you can't see any problem, but on the inside you can see that time is important. That is, the list objects always work as functions, but because the variables list and max change values, they don't work as functions - you have to think about time whenever you think of them. It would be easier if you only had to look at the method parameters to see the values, instead of having to trace changes in your head. This is a small-scale version of the bigger problems caused by things that change. We can probably deal with this version with no real problems, but let's follow through and see what happens when we apply the large-scale thinking to the small scale. Because a list is a recursive data structure, it turns out to be quite easy to rewrite max as a recursive method:

public int max(Link<Integer> list)
{
    return new Object()
    {
        public int max(Link<Integer> remaining,int current)
        {
            return remaining==null ? current : max(remaining,Math.max(current,remaining.item));
        }
    }.max(list,Integer.MIN_VALUE);
}
Woah! I'm abusing inner classes or something! What's going on? Java doesn't let you define a method inside a method, but it lets you define a method inside a class, and a class inside a method, so that's what I've done. If I was going to write it in more idiomatic Java, I'd do this:

public int max(Link<Integer> list)
{
    return maxImpl(list,Integer.MIN_VALUE);
}

private int maxImpl(Link<Integer> remaining,int current)
{
    return remaining==null ? current : maxImpl(remaining.next,Math.max(current,remaining.item));
}
Now that you've understood that these two idioms are actually equivalent to each other, you can read the first one without any confusion. Just understand that if I could declare a method inside a method directly, I would have done. There is a problem with this code, in that it throws a StackOverflowError for medium-sized collections, on the Sun JVM, but not IBM's, so I am only using it as an intermediate case for this blog post, before reaching a final conclusion. Anyway, let's move on and create a similar method that gives the minimum for a collection.

public int min(Link<Integer> list)
{
    return new Object()
    {
        public int min(Link<Integer> remaining,int current)
        {
            return remaining==null ? current : min(remaining,Math.min(current,remaining.item));
        }
    }.min(list,Integer.MAX_VALUE);
}
I copied and pasted the code, then changed it, which is a good sign that there's some thinking left to be done. I can make more of it the same by renaming the method inside the anonymous class to 'invoke' or something equally generic. I can move the starting value to the method header - it might not make sense to everyone that the minimum of an empty list is Integer.MAX_VALUE, let's allow the user to decide what value that should be:

public int min(Link<Integer> list,int minimum)
{
    return new Object()
    {
        public int invoke(Link<Integer> remaining,int current)
        {
            return remaining==null ? current : invoke(remaining.next,Math.min(current,remaining.item));
        }
    }.invoke(list,current);
}
There's no reason now not to use the outer method as the target for recursion instead of creating an inner one, so if the anonymous class annoyed you, it goes away now:

public int min(Link<Integer> list,int minimum)
{
    return list==null ? minimum : min(list.next,Math.min(current,remaining.item));
}
Wow, that's short. It's also fairly simple. It says, for an empty list, return the given minimum. For a non-empty list, return ourselves invoked with a smaller list, giving the new invocation a different minimum. Notice that nowhere here have we changed any variables. Still, this throws a StackOverflowError too. Two more steps and we'll get rid of it. The only parts that are specific to minima now are the name of the method, and Math.min. A more general version of what we're doing here is reducing a list to a single value. There are lots and lots of reasons we might do that. Asking whether a list contains a certain item is a reduction.

interface Reducer<T,R>
{
    R reduce(T left,R right);
}

public <T,R> R reduce(Link<T> list,R accumulator,Reducer<T,R> reducer)
{
    return list==null ? accumulator : reduce(list.next,reducer.reduce(accumulator,list.item),reducer);
}
A Reducer is something that knows how to reduce 2 values to one. It doesn't necessarily have to mean two items from the list, just an accumulator and one item from the list. Let's have some imaginary syntax meaning that if I type Math.min with no parentheses, I get a Reducer<Integer,Integer>: int min=reduce(list,0,Math.min); That says find me the minimum value in that list, using Math.min to do so. Unfortunately, Java doesn't support such syntax, so this is what you really end up with:

int min=reduce(list,0,new Reducer<Integer,Integer>()
{
    public Integer reduce(Integer left,Integer right)
    {
        return Math.min(left,right);
    }
});
Unfortunately, this is pretty annoying - so annoying that if you use it more than once, you'll want to wrap the reducer up in a static field or method somewhere, so you end up with: int min=reduce(list,0,Maths.minRef); I'm English, we say Maths instead of Math, which turns out to be a handy conflict resolution here. We still have the StackOverflowError problem, but we can resolve it by rewriting reduce in the 'old' way, with changes to variables. Note that StackOverflowError is really a fault with Java, because at the point where reduce calls itself, there is no need to retain any of reduce's data on the stack. Java could make it work so that reduce overwrites its own parameters and then does a goto to get to the top. Unfortunately, it doesn't, so we have to do that ourselves (except the goto is some loop or other):

public <T,R> R reduce(Link<T> list,R accumulator,Reducer<T,R> reducer)
{
    while (list!=null)
    {
        accumulator=reducer.reduce(accumulator,list.item);
        list=list.next;
    }

    return accumulator;
}
So even though we've ultimately had to make a concession for the technical problems of being in a JVM, we've got something pretty reusable out of the thought experiment. Of course this is nothing new. I actually wouldn't at this time recommend using linked lists in this way in Java, but closures in Java 7 and a solution to the problem of tail-call elimination might make this much more attractive. 2. Cyclic data. If class A needs to hold a B, and B needs to hold an A, there's no way to instantiate them both at the same time. There are clever tricks that make them nearly instantiated at the same time, but you can't make the respective fields final in each. A common solution is to get rid of the cycle by creating a third object, C, that holds A and B, supplying the instances of each other as necessary. Unfortunately, the name for C is often hard to think of, which is a reasonable sign (I'm contradicting another of my blog posts here) that C is a bad thing to have at all. I'd suggest looking at the individual case and deciding what to do. Sometimes it's just that A and B should be merged, or that some functionality should be moved from one class to another. In other cases, it might turn out that some methods can be made static, in which case there's no need to hold an instance. 3. Data that will change over time. Essentially a philosophical question, it is possible to argue that something that is different before a certain time than after it hasn't changed, that there are actually two objects. Monads are a way of treating immutable objects as if they can change, by making the new value replace the old value seamlessly, which effectively solves the philosophical question by letting you write code nearly the same way regardless of the answer. Using Java, though, I'd probably suggest that if data changes over time, you may as well use mutable data. Perhaps Java 7 will make monads more attractive.

Wednesday, July 18, 2007

Remaining Nameless

In college, I came across some budding Pascal programmers with hundreds of lines something like this:

    gotoxy(12,13);
    write('|');
    gotoxy(12,14);
    write('|');
That's right, they were hand-coding menu systems in ASCII. I actually didn't spot this as being such a great problem at the time, because I couldn't see past how ridiculous it was not to make a procedure called, say, printxy, to do the above.
   printxy(12,13,'|');
   printxy(12,14,'|');
I got a couple of these students to do that, but they didn't really know why. After all, their editor had copy and paste, and everyone else was doing the same as them. Probably their teacher was, too, but I never looked into that.

What happened when they realised that all their '|'s were off by one? They edited each line of code.

Some of those students are now successful (in that they make money) IT professionals (in that they make money), so I can only assume that they learned something in the intervening years.

The rest of education, in the meantime, has changed a little. Students now come along with the word 'reuse' on their tongues. It's a magical thing, and they joke that it means copying and pasting, but they know it doesn't. They can't do it though - the novices anyway. They still copy and paste, like those of my time, sometimes guiltily. Mainly they don't actually understand the alternatives. Even more experienced programmers will struggle to avoid copying and pasting in some situations, and introduce false abstractions to do that. Languages are partially judged on how much repetition they force you into.

Going back to the Pascal example before - printxy wasn't a particularly bad name, but imagine that you're a bit of a weak programmer, and you have a small friend group who usually help each other, the infinite monkeys' approach to assignments. Your friends have never heard of printxy before, and look at your code like it was written by a Martian. You don't want that, so you'll keep your code as it is, despite what that weird Ricky suggested at lunchtime.

At this point, the text editor isn't really very useful. You cannot keep your friend group and me happy at the same time. You could probably write an editor macro that let you type printxy(x,y,'['); and converted it into the appropriate code, but it would be a one-way transformation.

What you'd like, because you want to get help from me and from your peer group (infinite monkeys plus a programmer might equal higher marks!), is to be able to maintain two views of the same code.

That is, you'd like to type printxy(x,y,'[') and have it converted into a gotoxy and write call, but have the editor still know that it's a printxy call, so that you can flick a switch and Ricky can see 'his' version.

This never happened, because the editor didn't support it. The only students who I spoke to who ended up using printxy were smart enough that they didn't depend on a peer group. Except Dave, who tried to depend on me instead.

Suppose that printxy was a particularly bad name, or the implementation of it was a bit more intricate (this is perfectly possible - it would make sense to reset the cursor to 0,0 after writing each bit of text, because on DOS screens the cursor is usually visible - having it flick around the screen is particularly distracting).

It'd be good if, whenever people wrote similar code (either through finger-typing or copy and paste), their environment picked up on it and made it into an abstraction. E.g.:

   gotoxy(12,13);
   write('[');
   cursor(0,0);
   gotoxy(12,14);
   wr..
At that point, the environment could start autocompleting the write and cursor calls, and if the user started to type gotoxy again after the next write and cursor calls, the environment could complete the whole three-line form, placing the cursor in the right places to edit the parts that were different between the first and second times.

Further, the environment could fold the blocks of code, just showing the first one and then the differences:

   gotoxy(12,13);
   write('[');
   cursor(0,0);
   ..gotoxy(12,14)..
   ..gotoxy(12,15)..
Then if the user starts editing one of the forms, the others should be edited in parallel, unless the user makes a specific gesture not to, or manually 'ungroups' a form. Groups could be shown via highlights in the margin, just as they are in some environments for an individual method, etc.

This would allow new programmers to start seeing abstractions appear before they even know what the word abstraction means, and more importantly, without even having to give a name to it. printxy would be something they applied later.

The missing half-dimension of code

In most programming environments, you're restricted to what I'll call one and a half dimensions. The vertical scrollbar is fine, most people will happily scroll a couple of screens down, but never sideways. In most languages, 'arrow-like' code is discouraged as being hard to read. It's a bit like humans wandering around in 2 dimensions, not really being able to wander freely in the air. Code is the same - take it away from the top-level unit (function, class, method), etc., and you're just waiting for it to collapse back down.

The more nested the code is, the harder it is to understand, because you need to take the more polluted namespace into account. If you declare x outside a form, declare x1 inside it, then sometimes forget to use x1, you'll be using the wrong value. It's only because there is no independent namespace.

Programming environments could help a little with this by warning you when you use something from the surrounding namespace, but sometimes you mean to. They could use a different colour instead of warning you. I think it's worth looking at why arrow-like code happens, to find a solution.

I think it's because there's nowhere to store unnamed snippets of code. Imagine a programming environment, where, when you typed a nested form, such as a lambda expression (or anonymous class, or anonymous function), the environment made it appear dislocated from the code that uses it, possibly connected via dotted lines, etc. Any variable that is used from the surrounding namespace can be shown specially, or as some kind of parameter. You could drag the snippet to another block of code, from where it could be used again. Any variables that the snippet needs that the first scope provided, can be either defaulted or new links can be made. This wouldn't even need the snippet to have its own names for variables.

Past the user interface layer, Lisp macros with generated (and hidden) names could easily be used.

You may be wondering why ordinary methods/functions as in most languages can't be used - they can, but not in all the same ways. For example:

for (int a=0;a<100;a++)
{
   if (x[a]<50)
      return;
   print("here");
   if (y[a]<25)
      return;
}
Here the if..return is the repeating part - there's no way of encapsulating that in a method/function, without changing the code a lot.

I'm not saying that naming abstractions is bad, but that being forced to name them is bad. I plan to come up with an environment for editing code in this way. It probably will be based on an existing language, using generated names that the developer doesn't see.

Slava Pestov pointed me at subtext as an existing implementation of something like what I want. It looks interesting, but I don't think there's a huge gap between it and what Excel would be if you made cells part of a tree instead of a grid.

Friday, June 29, 2007

On how the lack of macros damages Java code

Update - commenters pointed out an obvious mistake - I should have kept the sample code here the same as my real code. I've updated the code samples. Some time ago I asked why unit tests use assertions instead of returning a boolean. I didn't get any particularly convincing answers, so I continued returning a boolean, in my home-grown test framework, that's so small it hardly deserves the name 'framework'. One obvious benefit from using exceptions is that you get the name of the test method and class in the exception output. In my framework, I had to explicitly supply that. Each test object had a getName(). return "TestUninstallingDrivers". Ok, now I have duplication:


public static final UnitTest testUninstallingDrivers=
    new UnitTest()
{
    public boolean test()
    {
        stuff..
        return !card.hasDrivers();
    }

    public String getName()
    {
        return "testUninstallingDrivers";
    }
};
The usual "Java programmer" approach would be to just go back to exceptions, then you'd be able to get your IDE to show you the test method by clicking on the stack trace. However, there were some reasons not to go back to exceptions. I'd instead like to generate the getName() implementation based on the field name. I believe at least 2 out of the 3 major IDEs can help me with some kind of template like this:

public static final UnitTest $x=new UnitTest()
{
    public boolean test()
    {
        //Auto-generated method stub.  To stop this
       //annoying message, go through some dialogs
       //that you never really wanted to anyway.
        return false;
    }

    public String getName()
    {
        return "$x";
    }
}
So, that's all well and good, until I start refactoring, because the IDEs do not carry on linking the two expansions of $x even after the template has been applied. When I first heard someone rave about IDEA's Live Templates, I assumed they would provide such linking - they do not. Plus, even if they did, you'd still see the generated code, which isn't really that useful. The only part of the above code that's relevant to me is the name of the class and the code inside test. That is, I'd be happy with:

unitTest(testUninstallingDrivers,
{
    stuff..;
    return !card.hasDrivers();
})
..which would generate the above usual Java code. Of course, should I want to see the expanded template, I could just right-click on the template name or something. So what I'd really like from IDEA's Live Templates is for the template's name to stay in my source code, and to be expanded for compilation. But then, if it's staying in my source code, I can't compile without IDEA, or even with IDEA on another computer (unless I successfully manage my project settings). It would be better if the template could stay in my source code too. The source for the template. E.g.:

template unitTest(name,body)
{
    public static final UnitTest <name>=new UnitTest()
    {
       public boolean test()
       {
           <body>
       }

       public String getName()
       {
           return "<name>";
       }
    }
};
This would need a preprocessor before the usual Java compiler. There are some difficulties, like the <body> expansion above generating two sets of braces, but they can be resolved (a syntax like <@body> to splice in the body). In case there's anyone out there who hasn't recognised this yet, I'm really talking about Lisp macros, and not even a significantly complex application of them. I don't see any reason why modern programmers don't use a decent macro system, pretending to be happy with 'Live' Templates, and refactoring everything at a higher level (such as changing the unit test framework to use exceptions) instead of working with the actual source code they like. For a Lispy implementation of a unit test framework (in 26 lines of Lisp!), see this chapter from Practical Common Lisp.

Monday, June 25, 2007

Book Review - Release It! Design and Deploy Production-Ready Software

Release It! Design and Deploy Production-Ready Software, by Michael Nygard (Pragmatic Programmers) You know the drill. Here's a sample case of how something went wrong in production. The author needs to pad out the book, let's make the case more convoluted. Maybe include some code. A book written in dry technical English, painful to write and worse to read. That's what I expected when I received this book, except for the 'Pragmatic Bookshelf' logo on the front. I was pleasantly surprised; none of the above apply. The book took me quite some time to get through, not because it's padded out, but because it's dense. Despite being written in plain (and sometimes overly American) English, a lot of information is presented, and very readably. The author has clearly spent a lot of effort in making sure that the book doesn't patronise, yet does explain its terms clearly. Even though I'm not exactly the target market for this book, as it is aimed at enterprise developers (the author defines enterprise as systems that cost money whenever they go down), I enjoyed it, and I can apply quite a lot of it to my lowly non-enterprise project. There are a lot of references to Java in the book, but I don't think that should deter those who don't use Java, as the same points can be applied to other technologies. Rarely does it go deeply into Java-specific problems. Stop Waffling, And Tell Me What The Book's About Stability, capacity and operations. The stability part covers ways of making sure that errors in software don't spiral out of control. Even where there are failover subsystems in place, and everything seems isolated from everything else, there may be a hidden route of chaos, such that when one system goes down in a certain way, all the rest do. The 'Circuit Breaker' pattern will help to stop that. Capacity has a lot more human factors in it - how many sessions can your server support? Can you make sessions shorter in the event of a surge, saving RAM but annoying users? Does your testing environment match the production environment closely enough? Can you get away with static content for those users who are browsing, not buying? Do you really need pretty-printed HTML, adding 50K to data transfers? Operations is about ensuring that the administrators have an easy time of it, that you can have meaningful logs that are useful, that you can inspect (and even tinker with) a running application, throttling backups so that capacity isn't affected, and generally making sure that you can. A lot of the book may seem intuitive, but it's good to see your intuitions formalised, and taken a few steps further. Some programmers reading this book will be screaming out things like "use Erlang and this problem disappears", etc., and they'll often be right, but it's useful to understand a problem, even if your environment makes it impossible. Further, many problems will out in other ways even if an environment prevents the major cause. So I'd recommend this book to any programmer - learn from Michael's mistakes, and the mistakes of those around him, then hopefully your own mistakes won't be so costly. I'm glad that I keep the review copy, as I will be looking back through it again. Plus, I read some of it in the bath, so it's got a few crinkled pages - I don't fancy posting it back to anyone! The stories about what happened in production are always real, though the names are changed, and the author builds up a real sense of suspense that I've not seen often in technical books. The problems that he and his colleagues find are often hilarious, but the lessons drawn from them are important. I've often found, as I said at the start of this review, that stories in technical books are very dry, very boring and just padded out, but the author has enough writing skill, and great raw material, so that hasn't happened. To give you a flavour of how the book is written, here are a few randomish paragraphs:

Avoid fiddling Human intervention leads to problems. Eliminate the need for recurring human intervention. Your system should run at least for a typical deployment cycle without manual disk cleanups or nightly restarts.
It seems like common sense, but there are plenty of systems that require routine restarts. Common sense just isn't that common, it seems.
For example, I've seen badly configured proxy servers start re-requesting a user's last URL over and over again. I was able to identify the user's session by its cookie and then trace the session back to the registered customer. Logs showed that the user was legitimate. For some reason, fifteen minutes after the user's last request, the request started reappearing in the logs. At first, these requests were coming in every thirty seconds. They kept accelerating, though. Ten minutes later, we were getting four or five requests every second. These requests had the user's identifying cookie but not his session cookie. So, each request was creating a new session. It strongly resembled a DDoS attack except that it came from one particular proxy server on one Navy base.
Would you have thought of that in advance? I wouldn't, I'd have just blocked the user automatically, assuming malice.
Amazon ran into trouble with the Xbox 360, too. In November 2006, Amazon decided to offer 1,000 units for just $100. News of the offer spread far and wide. Not surprisingly, the 1,000 units sold within five minutes. Unfortunately, nothing else sold during that time, because millions of visitors hammered on their Reload buttons, trying to load the special offer page and score a huge discount on the hot console.
The context here is attacks of self-denial, where systems get attacked by themselves, by a special offer attracting an incredible surge of page requests. Again, I'd recommend this to any programmer, and to any administrator who deals with bespoke solutions. Perhaps if all you do as an administrator is install/configure applications for which a support contract exists, and you can afford the time between a problem and the support engineers appearing, then you won't benefit from this book. But then surely you're only 5 minutes away from being replaced by a shell script.. The one missing part, for me, is a discussion of how to go about designing a system from scratch - all the case studies describe existing systems, and often only a small part of them - I'd like some suggestions on how to write a system that will be able to scale easily - and how to avoid writing systems that won't.

Thursday, June 21, 2007

Missing Refactor - Convert to Anonymous Class

I'm still looking through my source for stray uses of 'private', following on from my recent blog about removing private, favouring other forms of encapsulation. One way I like to remove private is by converting named implementations of interfaces into anonymous ones. Here's some real code that I want to change:


public final class EthernetCableIcon implements
  ActionListener
{
  private final MouseInputListener listener;
  private final GUIContext context;
  private final JToggleButton button;

  private EthernetCableIcon(final GUIContext context)
  {
    button=new JToggleButton
      ("Ethernet Cable",EthernetCableHandler.icon);

    this.context=context;
    listener=new MouseInputListener(context,button);

    button.setVerticalAlignment(SwingConstants.CENTER);
    button.setVerticalTextPosition(SwingConstants.BOTTOM);

    button.setHorizontalTextPosition
      (SwingConstants.CENTER);

    button.addActionListener(this);

    button.setToolTipText("Click on this to draw an "+
      "Ethernet Cable, then drag on the display to "+
      "make one appear");
  }

  public static JToggleButton newButton
    (final GUIContext context)
  {
    return new EthernetCableIcon(context).button;
  }

  /**
   * Replaces the NetworkView's mouse listeners with its 
   * own, so that the EthernetCable can be dragged
   * without causing other problems.
  */
  public void actionPerformed(final ActionEvent event)
  {
    final Component view=context.getNetworkContext()
      .networkView;

    if (button.isSelected())
    {
      context.getNetworkContext().toggleListeners.off();

      view.addMouseListener(listener);
      view.addMouseMotionListener(listener);

      view.setCursor(new Cursor(Cursor.HAND_CURSOR));
    }
    else
    {
      view.removeMouseListener(listener);
      view.removeMouseMotionListener(listener);

      context.getNetworkContext().toggleListeners.on();
      view.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
    }
  }
}
My IDE, IntelliJ IDEA, has lots of refactorings, including from anonymous to nested, from nested to inner, moving classes, etc., but has nothing for making this an anonymous class. It's used precisely once, from the static method newButton. I've refactored it by hand, which isn't too bad, but it does make me wonder why I have to. Eclipse never supported this refactor either. Post-refactor:

public final class EthernetCableIcon
{
  public static JToggleButton newButton
    (final GUIContext context)
  {
    final JToggleButton button=new JToggleButton
      ("Ethernet Cable", EthernetCableHandler.icon);

    final MouseInputListener listener=new
      MouseInputListener(context, button);

    button.setVerticalAlignment(SwingConstants.CENTER);
    button.setVerticalTextPosition(SwingConstants.BOTTOM);

    button.setHorizontalTextPosition
      (SwingConstants.CENTER);

    button.addActionListener(new ActionListener()
    {
      public void actionPerformed(final ActionEvent e)
      {
        final Component view=context.getNetworkContext()
          .networkView;

        if (button.isSelected())
        {
          context.getNetworkContext()
            .toggleListeners.off();
          
          view.addMouseListener(listener);
          view.addMouseMotionListener(listener);

          view.setCursor(new Cursor(Cursor.HAND_CURSOR));
        }
        else
        {
          view.removeMouseListener(listener);
          view.removeMouseMotionListener(listener);

          context.getNetworkContext().toggleListeners.on();

          view.setCursor
            (new Cursor(Cursor.DEFAULT_CURSOR));
        }
      }
    });

    button.setToolTipText("Click on this to draw an "+
      "Ethernet Cable, then drag on the display to "+
      "make one appear");
    
    return button;
  }
}
Whether it's more readable now probably depends on the reader, but it certainly doesn't need private and hasn't lost anything in the encapsulation. I find it slightly more comprehensible anyway.

Tuesday, June 19, 2007

Taking private out of code without losing encapsulation

When I started programming in Java, I took private and public as fairly necessary access levels. It's only in the last couple of years that I've realised that you can achieve better encapsulation than private - by making the variable disappear, or at least not have a name in the relevant scope.

As an exercise, I thought I'd take a look at my codebase and see how it is impacted if I get rid of private. But of course, I didn't want to expose implementation details either, so I did it with the power of thought, a scarce resource.

Low-hanging fruit first: Private constructors. Sometimes these are used to prevent instantiation of a utility class. IDEA actually warns me if I instantiate a utility class, so I don't need the constructor. It's a no-brainer to delete unused code.

Ok, now private fields with get/set methods. There are two kinds - the first is the simple problem of having a private field for no reason - the get and set methods just pass through to the variable with no checking. Make the variable public and get rid of the methods. IDEA helps me with this - Ctrl-Alt-N inlines a method.

Private fields with more interesting get/set methods. In my code, so far, I don't have any interesting get methods, just some set methods that do some work after the value has been set. This isn't an original idea:

Make a Property interface, using generics (no evil casting) with get, set and addPropertyListener. Provide an implementation as a static factory method. Now change the private field to be a Property, adding the logic from the set method to the Property via a PropertyListener. Fix the get and set method so that they delegate to the Property, make sure everything compiles, then inline the get and set methods. If your get and set methods are more interesting than mine, then perhaps you'll need a more advanced Property type, e.g., addPrecondition, addPostcondition, etc.

Now for the fruit at the top of the tree. I use a Map to allocate IDs for Cables (it's a network simulator, and the IDs are useful for the event log). I don't want to expose the Map, but I do want to expose the operation I have on it - cableIDFor(Cable cable). How can I do that without using private? The Map has to persist between invocations, so I can't create it inside cableIDFor.

I'll make a field, called cableIDFor. It will hold an object that has one method. That method will take in a Cable and return an Integer. In other words, it's a Function<Cable,Integer>.


public final Function>Cable,Integer> cableIDFor=
    new Function<Cable,Integer>()
{
    final Map<Integer,Cable> cableIDs=hashMap();
 
    public Integer invoke(Cable cable)
    {
        for (final Map.Entry<Integer, Cable> entry: 
                cableIDs.entrySet())
            if (Caster.equalT(entry.getValue(), cable))
                return entry.getKey();

        for (int a=0;;a++)
            if (!cableIDs.containsKey(a))
            {
                cableIDs.put(a, cable);
                return a;
            }
    }
}
You call that like so: cableIDFor.invoke(cable), and of course now you get it as a Function for free, so if you want to pass it to some other method, you can. Oh, and yes, it's not a pure function, but I know that and treat it accordingly.

Thankfully I only call cableIDFor in one place, so I don't mind that IDEA doesn't provide an automated refactoring for this. Perhaps the structural search and replace will do it.

One more, a small one. I have a private field in a class that implements IncomingPacketListener - it's a StringBuffer, used for unit testing only. Easy solution, make the class anonymous and the name of the StringBuffer variable disappears from relevance.

I haven't lost any encapsulation in any of this, so I'm quite pleased. This all makes me realise that it isn't a problem that Common Lisp's OO support doesn't include private. That might actually be a good thing.

I expect a lot of people will be thinking "No! You're losing flexibility", but that's just not true. None of this code is external - I'm not actually impacting anything outside my own codebase. Externally-facing code gets put in separate projects that I normally leave closed so that I don't mess with it by accident. So, suppose that I decide that one of my public fields does need some validation - I can use IDEA's refactoring to encapsulate it, and then convert it into a Property or leave it as a private field with get/set. I'm not losing anything.

It's not less readable either. Because I use bits of functional programming in my code, it's actually fairly useful to be able to refer to a 'method' without executing it, which I can do if I convert it to a field that holds a Function. I end up with less anonymous classes this way. Likewise, even for 'normal' programmers, it's useful to be able to refer to a property instead of grabbing its value, for instance, for binding to a graphical object, etc.

Wednesday, June 13, 2007

Improving Your Visitors, and a Request For More Autoboxing in Java 7

Prior to Java 5, there was one really common way of implementing the visitor pattern. I'll use my network simulator as an example, defining a visitor that can visit any kind of network component (a card, a cable, a hub or a computer):

public interface Visitor
{
    void visit(Card card);
    void visit(Hub hub);
    void visit(Cable cable);
    void visit(Computer computer);
}
and an example accept method:
public void accept(Visitor visitor)
{
    visitor.visit(this);
}
For those not initiated with how this works, here's a typical example:
public static void drawAComponent
       (NetworkComponent component,final Graphics graphics)
{
    component.accept(new Visitor()
    {
        public void visit(Card card)
        {
            graphics.drawRect(10,10,20,20);
        }

        public void visit(Computer computer)...
    });
}
It works quite well, and you can adapt it to make it work over a collection. In IPSim there is a tree of components (each component knows its children, and there is a collection of top-level components). So you can do:
network.visitAll(new Visitor(){etc.});
If we want to inspect the object (get a value back from it) rather than do something, then we end up with code like this:
public static Dimension getSize(NetworkComponent component)
{
    Dimension[] result={null};

    component.accept(new Visitor()
    {
        public void visit(Card card)
        {
            result[0]=new Dimension(50,60);
        }
        etc.
    });

    return result[0];
}
Clearly it would be useful if the visitor could return something instead of having to set some value. We could make the Visitor's methods return an int, but then we'd have to write it again if we later needed another type. There are two solutions to this: 1. Make the methods return Object. This obviously results in casting, which we all know is for magicians. Let's move on to Java 5. 2. Make the methods return T, where T is a type parameter on Visitor. Ok, easy:
public interface Visitor<T>
{
    T visit(Card card);
    T visit(Cable cable);
    T visit(Hub hub);
    T visit(Computer computer);
}
and the accept method:
public T accept(Visitor<T> visitor)
{
    return visitor.visit(this);
}
The only problem with that is that T is undeclared in the accept method. Don't make the mistake of declaring it on the class (class Card<T> implements NetworkComponent<t>), because then you'll only be able to use one type of Visitor with each instance you create. Declare it on the method:
public <T> T accept(Visitor<T> visitor)
{
    return visitor.visit(this);
}
Now you've got something more useful, the above clunky code becomes:
public static Dimension getSize(NetworkComponent component)
{
    return component.accept(new Visitor<Dimension>()
    {
        public Dimension visit(Card card)
        {
            return new Dimension(50,60);
        }
        etc.
    });
}
This becomes much more interesting when you apply it across a collection. Instead of writing code that iterates over all the components and does something, we can write code that generates a result. For example, suppose I want to know if any of my components are a crossover cable. I want to visit all the components, and return true if any of them are a crossover cable. I could store a list of booleans, to process later, but that would be wasteful and indirect. What I want to do is apply the || operator between each pair of results.
public static boolean areAnyCrossover(Network network)
{
    return network.visitAll(new Visitor<Boolean>()
    {
        public Boolean visit(Cable cable)
        {
            return cable.isCrossover();
        }

        public Boolean visit(Computer computer)
        {
            return false;
        }

        public Boolean visit(Card card)
        {
            return false;
        }

        public Boolean visit(Hub hub)
        {
            return false;
        }
    },new Combinator<Boolean,Boolean>()
    {
        public Boolean combine(Boolean one,Boolean two)
        {
            return one||two;
        }
    });
}
Whew. This is an implementation (or at least behind the scenes there is one) of the 'reduce' algorithm, plus a bit of mapping going on first. It's very flexible. There's quite a bit of boilerplate above though, and as the number of component types grows, the amount of boilerplate grows and grows. The usual solution is to make an abstract class with empty (return null;) methods for each visit method, which you subclass to customise. That works pretty well (remember the @Override annotation!), but I've been avoiding subclassing for some time now, so I immediately started to wonder whether there was another way to do this. I'm not a zealot, if I didn't find another way, I'd just subclass. I found another way..
public static boolean areAnyCrossover(Network network)
{
    return network.visitAll(new DefaultVisitor<Boolean>()
        .visitCards(new Function<Card,Boolean>()
        {
            public Boolean invoke(Card card)
            {
                return card.isCrossover();
            }
        })
        .visitAnythingElse(new Function<NetworkComponent,
            Boolean>()
        {
            public Boolean invoke(NetworkComponent any)
            {
                return false;
            }
        }),new Combinator<Boolean,Boolean>()
        {
            public Boolean combine
                (Boolean one,Boolean two)
            {
                return one||two;
            }
        }
    });
}
Ok, it doesn't look brilliant, but it does look a little like functional programming. Let's make these anonymous classes look more like functions:
public static boolean areAnyCrossover(Network network)
{
    return network.visitAll(new DefaultVisitor<Boolean>()
        .visitCards({Card card => card.isCrossover()})
        .visitAnythingElse(
            {NetworkComponent component => false}),
        {Boolean one,Boolean two => one||two});
}
One more improvement would be if it were possible to get at || as a function. Let's imagine that #|| works for this. Let's also imagine that closures allowed you to elide unused parameters, that type inference were supported, and that method references were supported (!):
return network.visitAll(defaultVisitor
    .visitCards(Card#isCrossover())
    .visitAnythingElse({ => false}),#||);
Interestingly, it still looks like Java, and it doesn't get bloated whenever you add a type. I don't suppose for an instant that Java 7 will go this far. For an example of the <T> visitor pattern in current Java, see the source code for javac. It's littered with them, and it's quite nice to work with, but at least for now, remember your @Override.. And back to normal Java, suppose you implement Visitor<T>, but then come across those cases where you don't want to return something.
void doSomething(NetworkComponent component)
{
    component.accept(new Visitor<Void>()
    {
        public Void visit(Card card)
        {
            whatever.
            return null;
        }
        etc.
    };
}
I'd like to be able to use my Visitor type with a <void> type parameter, but I cannot. Please, if you got this far, and are Neal Gafter or someone else relevant, consider allowing primitive generic type parameters. As far as I can see, this can all be done at the compiler level, making a Visitor<void> appear as a Visitor<Void> in bytecode. At the moment, I often implement two Visitor types for each hierarchy - one returning void, and one T. Perhaps that's overkill, but it reminds me that it's a workaround.

Monday, May 28, 2007

Optional Checked Exceptions - Spitting at the compiler

In further anecdotal evidence that Gilad was right, Neal Gafter has blogged with a suggestion that checked exceptions could be removed from Java. He's right, they could. As far as I can see, all existing code would still compile, and what's more, it would actually work with existing bytecode with no problem, as the runtime has no problem with throwing undeclared checked exceptions. I've thought for a while that the problem with checked exceptions is that the API that throws them doesn't know whether you will care to deal with them.

First, I'll mention some ways in which closures can help with checked exceptions, then a mechanism for optional checked exceptions:

Reader.close() can throw an IOException, but we don't let it propagate. Closures to the rescue:
suppressing(IOException.class){ reader.close();}

Making Swing use the native look and feel requires catching about 5 exceptions, but we don't care about any of them:

loggingAndIgnoring(Exception.class){ UIManager.setLookAndFeel..}

Or even better:

whenExceptionsHappen({e => e.printStackTrace();}){ UIManager.setLookAndFeel...}

Suppose that we do want to propagate the exception instead, but we don't want to wrap it in a RuntimeException:

public void readsFromAFile() spits IOException

I'm not seriously suggesting 'spits' as a keyword, feel free to think of your own (I also like 'farts' and 'vomits', but that's because I've had a very busy weekend), but in this context, a method that spits IOException is declaring that it can throw an IOException, but that callers of it do not have to catch the IOException. That way everyone can be reasonably happy. API designers can still declare their exceptions using throws, guaranteeing that the client programmer has to think about the exception, but the client programmer can prevent the exception from leaking through their codebase, by using spits.

There is one problem - catching a checked exception from code that does not throw that exception is currently a compile-time error. Spat exceptions would make that compile-time error need to disappear too.

Challenge: think of a better keyword than 'spits' for this.

Thursday, May 24, 2007

You don't need TDD, you need a REPL

A walkthrough of how TDD can be badly applied to promote bugs, and an alternative. I'm imagining that my project is in Lisp, for the code samples, and so that I have a decent REPL (read-eval-print-loop, a place where you type code and see what it evaluates to). The situation described here is only partially based on reality, but you can judge how likely it is for yourself. 4:40pm Let's consider some code that we completely understand - adding two 2D points together. TDD says that I should write a test.. ok: (assert (equal (point+ (point 3 2) (point 4 6)) (point 7 8))) Then it says that I should make the test fail:

(defun point+ (first second)
  (point 1 2))
Ok, that fails. Now I should make it pass, and I should do the minimum required for that.
(defun point+ (first second)
  (point 7 8))
4:45 It passes. I get distracted by the telephone. 4:55 I look back, and I see that my test passes. Ok, I'm done, let's move on. None of my other tests use point+, because I try not to write dependent tests. So in this case, I will find the above bug in integration tests. But those involve files, and are a bit slower, so I don't bother running those quite so often. 5:00 My boss comes in and asks for a build for today's work, so that he can have a play around with it on his laptop on the train, which sets off in 10 minutes. I disable the integration tests temporarily so that I can just build it and give it to him, then dump a jar file to his USB pen drive. 5:10 He's on the train. 5:20 I'm distracted by the phone again. "All the drag and drop seems to have suddenly started going to the same place". Ok, I say, I'll fix it right now. So I re-enable all the integration tests, and yes, there's a failure. I fix it. 5:30 I email another build to my boss, but he's not able to get it until he's at home. While he was on the train, he gave a broken demo to a potential customer. You can find a few things wrong with my environment, such as that I don't use continuous integration, I actually answer phone calls while coding, and that I don't keep daily builds around for those times that my boss asks for a build. However, those are fairly superficial. The big problem that following TDD caused me was that I felt good about some really bad code. Without a test, I would have had suspicion for the code, but the test gave me confidence. That's not to say that testing is a bad thing, but that TDD gave me confidence in broken code. So let's implement the same thing again, but with a more 'distraction-proof' testing technique: 4:40 Write the function:
(defun point+ (first second)
  (point
    (+ (x first) (x second))
    (+ (y first) (y second))))
4:45 Check that it works for a few values in the REPL: (point+ (point 1 2) (point 3 4)) > 4 6 (point+ (point 1 4) (point 5 10)) > 6 14 ok, seems fine. 4:50 Get distracted. 4:55 Return to the code, there's no test yet, so I don't trust point+. Oh, but wait, look at the REPL, it looks like it works. I run the tests in the REPL again, then write a test case. (assert (equal (point+ (point 3 4) (point 5 6)) (point 8 10))) The test case passes, and this time I haven't made incomplete code pass tests. My boss, on the train, is happy, and so is the potential customer he demoed the software to. A REPL helps me to separate code that's part of my project from code that is just being thought about. It encourages experimentation, and hence thought, but doesn't get in the way should you get distracted and come back. It also makes you less likely to put broken code into the codebase, because it doesn't make you write experimental code in the production code.

Tuesday, May 22, 2007

I'm a Twit Too

After diligently avoiding finding out what twitter was, although it's hard to ignore it if you read technical blogs, two of my friends started using it and I joined them. It's amusing to see it go down every so often, and to think that Ruby is the culprit. Still, it goes down more gracefully than javalobby, and it's only lost one post of mine so far, which is a lot better than javaranch, and many blog sites. I'm going to keep mine technical, mainly on Java and Lisp at the moment, mainly as ideas for blog posts or projects that I'll probably never get around to. So if you'd like to steal my ideas, do whatever it is that twitter users do, or add the feed to your RSS reader. twitter ID - ricky_clarkson - http://twitter.com/ricky_clarkson

Thursday, May 17, 2007

Using just the JDK and 55 lines, I can find empty 'then' statements in Java code.

A few hours ago I noticed some comments on Joe Darcy's blog post about annotation processors.

I originally lost interest in annotations very quickly when I realised that annotation processors didn't have access to the full AST. I fiddled around with ANTLR a little, with CheckStyle, PMD and Findbugs' APIs to see what I could do. Not a lot, as it turned out. ANTLR looked promising, but as I recall, the language file for Java 5 was a bit flaky at the time. The others didn't provide me with complete types, so I couldn't detect things like code that tried to find a StringBuffer in a List of Strings. I gave up for a while, went off and learned to be productive in Haskell, and Lisp, and stuck my head into closures, which I'm very optimistic about.

I followed some links (about 6 deep) from Joe's blog, and came across the compiler API and compiler tree APIs. I have used it before, when I got some novice students to write their own compiling Java editor (that was fun), but I hadn't realised that you could get access to the actual compiler types - the standard API is rather thin. All you need to do is cast the task returned by the Java compiler, into a com.sun.source.util.JavacTask, and you're away.

I'm already mildly familiar with the compiler, having fiddled with its source a month or two back. I was trying to add a language feature that Stephen Colebourne, Stefan Schulz and I had been discussing, but we dropped the idea before I finished (well, before I really got started). Today I decided to attack a problem that used to catch me out when reading novices' code - an if statement with a semi-colon on the end, which just means 'if this, do nothing' and it executes the next statement regardless of the condition.

Javac uses the visitor pattern incredibly heavily, to a scale I've never seen anywhere else. I like it, but it caught me out temporarily. I don't really write subclasses anymore, I always use an alternative where practical. So I subclassed TreeScanner, which has nice 'return null;' implementations of every method, just ready for me to override. Which I didn't. Though I thought I was. The @Override annotation saved me when I realised..

Because I have my IDE set to Java version 5, and I wanted to run this code against version 6, I was just editing in vim and running from bash in Cygwin. No warnings about unused methods there then..

The short-term solution is to make sure I always remember @Override. The long-term, unlikely solution, is to persuade the javac project lead, sometime after Java 7, to accept my patch that makes these visitors more 'functional', so that instead of overriding, you give them a closure to invoke. The other advantage there is that you would be able to provide real booleans, rather than Booleans, etc.

There was only one more gotcha. Not only do I not subclass, I also don't use null very often, so I'd forgotten how to deal with boolean operators and null (I had to use Boolean, not boolean, thanks to generics). See if you can reduce my bestOf method into a chain of ternary operator calls. I couldn't do that without getting a NPE. I might investigate later.

There were no more gotchas. It was actually really easy, 30 minutes end to end. I included an 'empty' if statement in the source itself for testing. I think my next task should be to find places where @Override should be..

After all that fanfare, the code wouldn't fit in my blog's layout particularly well, so I'm afraid you'll have to click here to see it.

Monday, April 09, 2007

Really Own Your Code

Walking to the bus stop, with a coffee burning one hand and my breakfast the other, I noticed how poor my area looks; an urban area where many students and young professionals rent houses. The tenants aren't poor, the owners neither, but the area itself is impoverished, because the owners don't care and the tenants don't care. I got on the bus, and dropped half my coffee on the bus floor as it went over a speed bump, because I was holding the coffee so as not to burn my hand too much. Ah, well, glad it wasn't my bus. It struck me right there how little tenants look after the property they rent. Some local teenagers smashed a bottle of beer outside my house, and I didn't clear it up. I didn't ask the local authorities to do so either. I just looked at it with disdain whenever I passed it, and resented paying my local taxes even more. In my job as a coder, on a 1.5-man project, I am a tenant. I'm actually a good tenant, in that I look after the codebase pretty well, but I'm still a tenant in the most important, and crippling, way. I don't own my code. This isn't the same as responsibility for my code; I have that. It's my code, but it's not mine. I can't walk away from my employer and reuse the code elsewhere. That's not completely true; for a couple of libraries I wrote for the project my boss has given me licence to release them for free. For those libraries, I actually find myself reserving my best coding practices, because I know that other people will need to read the code. Not just in some abstract "sometime after I leave my job" way, but in a "they already do read it" way. I don't bother to create separate libraries for code that I can't release separately. In other words, I don't decouple as much as I could, because the practical benefits are too indirect. Realistically, I know that my project will die when I leave. That's not to say that I won't be very gracious in documenting it. My boss doesn't have the skills to maintain it well, and he's uncertain as to how to make more money from it, so he probably won't want to release the whole thing for free until it suffers from bitrot (which will probably be whenever IPv6 becomes dominant). The fact that I don't own the code means that my goals and the project's goals are slightly at odds with each other. There's an IP stack in the project, a serialisation library, clever handling of scroll bars when stuff is dragged around the display, but only our 200 students (per year) are benefitting from those. The funding comes from a nationwide education body, but they don't have rights over the code either. In that respect, it's a waste of money, because other establishments can't easily customise it for their requirements, and largely they don't know about it. In fact, even within our department, another member of staff wanted to use the software, and she couldn't, because it didn't have a particular feature. I offered to implement it, but my boss declined because it wasn't part of what the funding was paying for. If it was my code, I'd happily implement it in a separate branch, in my spare time, and I'd feel enthusiastic about it. Now let's look at the most recent entry in Bugzilla for this project: "A long term thing for a quiet Friday afternoon (if such a thing exists!) In the same way you have files in the jar for customisation of "installation number", "installed to" etc, I think there may be a long-term need to use a similar mechanism to allow some customisation of the conformance rules (this will be important if other people use IPSim, as there may be some things that I want to give feedback on that other people may not care about" We lost 150 users already by not doing this for the other member of staff. Plus, I could only code in advance customisations that I can anticipate. If I'm on holiday or busy coding a new feature that we already have funding for, we'll miss out on the opportunity. For a small project like this one, developer motivation and the quality of the project would increase if the developer could reuse the work elsewhere. That could mean open-sourcing it, as has been done for two small parts (a functional programming library and a Java layout manager), or it could mean an agreement not to use the code for commercial purposes for a fixed term after employment. How about for a larger team? I'd suggest to assign each source file to a single developer, who has responsibility over that file, and has actual ownership, so that he can reuse the file at some point, even now, in another company. Then any changes made by any other developer to that file are automatically licenced so that the owner can use them.

Wednesday, April 04, 2007

Is Josh Bloch the biggest problem for closures?

CORRECTION: Neal has since informed me that he, since the presentation that this post references, has learned that there is no such JCP rule. I'll still keep this post, because it makes some useful points (and so do the comments).

Josh Bloch, with "crazy" Bob Lee and Doug Lea, proposed their Concise Instance Creation Expression solution for closures for Java, last year.

They didn't address returning from the enclosing scope from within the closure. Theirs is a trivial syntax change, probably fairly straightforward to implement but it wouldn't address simple cases such as finding the first line in a file that matches an expression. If you're already familiar with why CICE is insufficient, feel free to skip past the code here.

Here's the psuedocode:


forEachLine ln in "/etc/passwd" do
   if ln contains "root"
      return ln
Here's the usual Java 5:

BufferedReader reader=null;
try
{
    reader=...;
    String line;
    while ((line=reader.readLine())!=null)
    {
        if (line.matches("root"))
            return line;
    }
}
finally
{
    if (reader!=null)
        try
        {
            reader.close();
        }
        catch (IOException exception)
        {
            log(exception); //but don't rethrow it
        }
}
So, of course, as the good programmers we are, we write an abstraction for that:

forEachLine("/etc/passwd",new LineProcessor()
{
    public void processLine(String line)
    {
        if (line.matches("root"))
            return line; //won't compile
    }
});
There's a problem there, the 'return line;' is returning from the run method, not the enclosing method. Ok, we can solve that, let's make LineProcessor return a String, which is normally null unless we want to end the loop. Then forEachLine can also return a String, which will be the return value of the method.

return forEachLine("/etc/passwd",new LineProcessor()
{
    public String processLine(String line)
    {
        return line.matches("root") ? line : null;
    }
});
This works, albeit with some strange semantics, which could be made more obvious by adding a class to hold the result, but that's not important for this post.

So forEachLine now has to know that the LineProcessor it runs might want to return early. When callers of forEachLine don't want to return early, they still have to return null all the time. It's inconvenient; to not punish callers that don't want to return early, we now need two versions of forEachLine, one that supports early return, and one that doesn't. That's confusing. The bad smell wafts up, making you either overload, or use names like "forEachLineWithAPossibleEarlyReturn".

What does CICE do for this?


return forEachLine("/etc/passwd",LineProcessor()
{
    return line.matches("root") ? line : null;
});
That's right. It removes a bit of punctuation and the 'new' keyword. Without underestimating that contribution, it doesn't actually help to make the end result resemble the psuedocode. It would be hard to get back from this end result into the psuedocode, there's a loss in translation. It isn't expressive.

The BGGA proposal allows this:


forEachLine(Line line: "/etc/passwd")
    if (line.matches("root"))
        return line;
Now just to remind you of the psuedocode again:

forEachLine ln in "/etc/passwd" do
   if ln contains "root"
      return ln
It doesn't need a special version of forEachLine for each use case. It's generally better, more expressive, with one wart that I'll mention at the end.

So why does this matter? Neal Gafter, the proposal lead, used to work for Sun, he's well respected, so he can easily make this into a JSR. Or not.

Neal Gafter now works for Google. All the work he's put into BGGA has been on his own time, it's not allowed to be his "20% project" (Google employees spend 20% of their paid time on ideas of their own). He is not the JCP's contact for Google. Surprise, surprise, Josh Bloch is, and Josh has his own more limited, less expressive, proposal, as I've demonstrated just now.

The JCP has a rule that disallows individuals from being on the JCP if their employer is on it. I felt sorry for Neal at the end of his presentation on closures at Google. Here's a quote from the last few minutes (emphasis from original):

From the audience: "Is someone planning on opening up a JSR on this?"

Neal: "There's a long answer and, I'm afraid, a longer answer. I was planning on writing a JSR for this. Sun Microsystems actually asked me to write a JSR proposal for this. But I can't do that, because I am not Google's JCP representative. And I cannot do it as an individual contributor to the Java Community Process, because as a Google employee I cannot be an individual contributor to the Java Community Process.

Google's JCP representative is Joshua Bloch, and he has other ideas about what should be done in the Java language in this space. As far as I know he is not currently planning on submitting a JSR on this. My hope is that creating a prototype, which by the way, I'm doing on my own time, will be something that Sun can use as a justification for Sun creating a JSR to do this into the language, because I think that's the only way this will happen in Java at this point."

Here's a little of Josh Bloch on closures:

"I like closures. I think they work very well in languages that are designed around them, like Smalltalk and Scheme and so forth. I think closures in java are a good thing. We've basically had them since 1.1 in the form of anonymous class instances and those are a bit clunky so I definitely see a place for improving support for closures; on the other hand some of the proposals that I've seen floating around are overly complex; they involve massive changes to the type system, things like function types and I'm severely worried about pushing the complexity of the language beyond the point where Joe Java can't use the language anymore.

If we add more support for closures I think it has to be in the spirit of the current support, which means that closures should take the form of instances, of types that have a single abstract method, whether they are interface types such as Runnable , or class types such as TimerTask. I think it would be nice if a better syntax in the current anonymous class syntax were adopted and if requirement with regards to Final variables were somehow made more tangible, which doesn't mean necessarily relaxed; I think it's actually good that you can not close over non Final variables, but it's a pain to actually mark them final, so if they automatically marked themselves final which would be nice."

His points are all good, except that function types aren't really a big overhaul of the type system - they will be resolved into interfaces. They're no bigger a conceptual problem than array types are.

Also, I think that if I could write a forEachLine in the BGGA style, I'd be more than happy for novices to use it.

The wart I mentioned is that Tennents' Correspondence Principle is violated by the BGGA when a closure throws a checked exception, and the interface that the closure conversion converts it to doesn't include any checked exceptions.

Neal proposes an extension to the generic type system to allow writing interfaces whose single method throws 0, 1 or many checked exceptions, but for those cases where the interface is already fixed, such as SwingUtilities.invokeAndWait(Runnable), the exceptions cannot be passed back to the caller. The code fails to compile. This is an inconsistency with the rest of the proposal. You can return from within a Runnable closure, but you can't throw a checked exception from within it.

I think that it would be possible to achieve exception transparency without needing anything special on the interface, as checked exceptions are purely a compile-time concept.

Blog Archive

About Me

A salsa dancing, DJing programmer from Manchester, England.