General musings on programming languages, and Java.

Monday, January 18, 2010

JNI + applets = pain!

I mostly work on GUI software for controlling and viewing video from security cameras. The software is written in Java, and mostly written by people who are no longer with the company. The usual app I work on is a Swing application, but there is also an applet, which displays just a viewer; the controls for it are HTML buttons around the applet.

We use MPEG-4 (and are adding H.264) extensively, and Java's support for that is, well, non-existent, so we use ffmpeg, via JNI bindings generated by SWIG.

If I was starting again, and for some reason still thought using Java was a good idea, I'd try xuggler out. Xuggler appears to provide the kind of wrapping library around ffmpeg that I would hope to evolve our code towards. But even Xuggler wouldn't fix these recent issues.

The first problem, which was mostly solved before I got involved, is that you cannot load a native library directly from your JAR file. You need to extract it (typically into java.io.tmpdir), and then load it. Not too hard, but it does start to feel icky especially when you consider that an abnormal termination of the browser will cause the file to be left taking up space until manually deleted.

The second problem is the strange interaction between classloaders and JNI - even within trusted code, two classloaders in the same JVM cannot each load the same library. I'm sure somebody somewhere thinks this is a feature rather than a bug. Our code does nothing fancy at all with classloaders; it just gets affected by the fact that two applets executed by the same browser instance will share a JVM. This is still true after Java 6 Update 10, in which the JVM that applets run in is no longer the same process as the browser. If the codebase that you specify to the applet tag is different between two instantiations of the applet, then each instantiation occurs in a different classloader, and the JVM prevents the second instantiation from loading the same library (from the same filename).

This wasn't too bad, and we changed our web pages so that the codebase was the same in each instantiation. As it happened, we weren't loading anything other than the applet jar itself, so that was quite okay.

The applets and web pages are hosted on our image servers, which are units that can deliver data from and to multiple cameras. So then when one browses from an applet hosted on one image server to an applet hosted on another, despite the codebase in the applet tag being the same, two classloaders are used, and the JVM prevents the second applet from loading its native library.

The obvious solution to this is to, when writing the native library to disk, choose a unique name. But that's where the third problem comes in..

Most of our users run Windows, and on Windows if you try to delete a .dll that is in use the OS prevents that. This time, however, the relevant users are all using Solaris, and Solaris allows the .so to be deleted even while it's in use. Our library-extraction code would try to delete libffmpeg-1.so, and if it succeeded (which on Windows would be because the library was not in use), it would then use that as the filename to give the library extracted from the jar file, and then load it. As you can probably see, this works well on Windows, and like a wooden saw elsewhere, because the JVM then believes two classloaders are trying to load the same library.

The fourth problem is that the applet is self-contained; we have a separate build for Windows, Linux, OS X and Solaris, so JavaScript in the web pages has to detect the OS. Detecting the OS is ok, but we support Solaris Intel and Solaris Sparc, and there's no way of detecting those (please correct me!) from JavaScript. We have a mechanism for dealing with this, but I'm not happy with it.

I do plan on making the applet no longer self-contained, so that we distribute one platform-independent section, which detects the OS it's on and loads the correct native library, but really, this is just a case where Java doesn't come with batteries included. I realise applets are not even on the backburner anymore; they've been behind the stove getting mouldy for years, but this does seem like something that should be a lot more straightforward.

An approach that looks promising is that of applet-launcher, which wraps your applet up in another applet that handles all the library loading. I couldn't try this easily as I only control the Java code, not our web pages - it would have required the addition of lots of .getSubApplet() calls in the JavaScript code.

Tuesday, December 08, 2009

Deleting code, what first?

I have about 200kloc of Java code to work with, and I often stumble across bits that are more complex than they need to be, costing me time when I'm trying to solve something else.

Within reason, having a smaller body of code is an improvement. Here are my guidelines, mainly for myself, to shrinking it.

1. Use IDEA's analysis tools to find unused code, and delete it. If it's public-facing API, and you know of no code that uses it, it's probably broken anyway. Deprecate it now and delete it at some later date. If you deleted it and somebody was using it, they'll complain at you, you'll reinstate it and include at least a comment that team X at company Y is using it, and at best an automated test that the code does what team X requires.

Watch out for main methods when you delete code - there are a few ad-hoc utilities in our codebase.

Always ensure that deprecated code is only called by deprecated code, i.e., that deprecation forms a clique.

2. Look at 'throws' clauses. If one low-level method has, say, 'throws IOException' in its signature, and all callers either pass it on to their caller or catch and do something dumb with it like logging, then you may as well do that within the low-level method, or rethrow it as a RuntimeException. This can remove a surprising amount of bullshit code.

3. Look for non-final static variables, a reasonable indicator of mutable singletons. Try to stamp them out. While this might actually increase the amount of code you have, it will do wonders for the maintainability. I did this today and found a potential bug (which I've yet to prove). The worst case is that you find out why you can't stamp a particular one out - you'll have learned something useful about the application's architecture and flaws along the way.

4. Use IDEA's "field could be local variable" inspection to simplify classes. As a general rule, a class with fewer fields is simpler.

5. Private getters and setters that do nothing beyond this.foo = foo; and return foo; are useless; inline them.

6. Search for repeated code; the IDEA Ultimate Edition can do this, but the Community Edition cannot. Unfortunately, it can only find them, not suggest a solution, and in my experience it doesn't get the ordering right; we had 15 almost-identical classes that it didn't even notice. It's still very useful though.

Even if you can't think of a decent abstraction, get rid of the repetition anyway. If needed, a better name or better way of doing it will be easy to use later. It's far easier to refactor 1 copy than 10 copies of the same code.

After a discussion at work, we decided that duplicated code has a cost proportional to its age multiplied by its size multiplied by the number of repetitions. That seems a reasonable rule; the cost is paid when using it or removing it.

7. Try to replace setters with constructor parameters, until it gets unwieldy or simply impossible as the objects get mutated after initialisation. When it gets unwieldy because the parameter list gets too long, consider splitting the class up.

8. Immutables remove the need for defensive copying. Lots of awful code is dedicated to copying values so that they can be passed to third parties. If you can make those values immutable this gets a lot easier.

9. Immutables remove the need for synchronization. Lock-free programming is far simpler if you can get away with it. Most programmers, myself included, get locks wrong, and the problems grow exponentially. That said, I don't have a general answer for what to do instead; I'm still at the stage where I need to work it out per-case.

10. Delete commented-out code. It's revision-controlled; if anyone actually ever remembers about it they can easily restore it. It's usually traces of previous experiments, and isn't of any real use. Similarly, delete the IDE-generated crap, like "Created on Mar 13 2005". You might want to keep the @author info, unless it's obviously useless, like @author Administrator, but even that can be of limited value years later when the author has left the company.

11. This isn't really about code, but: commit little and often. It's easy to do 3 refactors in one go and screw the third up, then have to revert and repeat the first 2. It's easier if you committed the first two. Similarly, if you find that a commit caused a regression, it's easier to work out what change caused it if each commit is small. That's not to say you should commit known broken code, at least not to anything other than an experimental branch.

In short: commits are game save points, not presentations.

Monday, November 30, 2009

My co-worker wouldn't get it

I'm continually unimpressed by a certain form of argument that I've seen in many places, but especially in the continuing discussions about closures in Java.

It goes like this: Feature X is great, and will make lots of code simpler, but there will be a lot of worse code because of it. Sometimes co-workers are mentioned, sometimes contractors who have to maintain the code without having months to learn its innards.

I think this boils down to two issues:

1. *I* would write bad code with Feature X.

2. I'm worried that I'll have to deal with bad code that uses Feature X.

Any healthy programming environment will not freeze code that is known to be bad in some way. It can be fixed, and lessons can be learned. If you seriously worry about your co-workers, watch their commits. If you worry about yourself, write some non-critical code that uses the feature a lot; perhaps a prototype, some unit tests or something unrelated to work.

With some exceptions, most programmers will write bad code before they learn how to write good code. Let them do so, and help them to get past it.

My co-workers would get it.

Tuesday, October 27, 2009

100 Bugs (ok, tickets) in 100 Days

I've now closed 100 tickets in the last 100 calendar days at work, which might not mean a lot, but it's been a personal target of mine to get to this point, so I'll celebrate it by, um, blogging!

Saturday, September 26, 2009

Which language shall we learn?

Hi Jose,

We decided, while drinking an overly-priced red wine the other night, that I'd help you to learn how to program, but without making it sound complicated. So, I thought I'd show you a few different language syntaxes and let you choose.

You can do anything you want with any of these languages, so feel free to pick the prettiest or whichever makes you laugh, or use whatever other criteria you feel like.

I chose the top-10 current mainstream languages, with the exception of PHP, which is too focused on one kind of task, and added Scala, Haskell and Erlang, because I like them.


1.
import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    System.out.println("Please enter your name.");  
    String line = scanner.nextLine();
    System.out.println("Nice to meet you, " + line + ".");
  }
}

2.
#include <stdio.h>

int main(int argc, char **argv) {
  char name[256];

  printf("Please enter your name.\n");
  scanf("%s", name);
  printf("Nice to meet you, %s.\n", name);
  return 0;
}

3.
#include <iostream>
using namespace std;

int main() {
  string name;
  cout << "Please enter your name.\n");
  getline(cin, name);
  cout << "Nice to meet you, " << name << ".\n";
  return 0;
}

4.
Module example
  Public Sub Main()
    Dim line As String
    Console.WriteLine("Please enter your name.")
    line = Console.ReadLine()
    Console.WriteLine("Nice to meet you, " + line + ".")
  End Sub
End Module

5.
#!/usr/bin/perl -w
use strict;
print "Please enter your name.\n";
my $name = <>;
chomp $name;
print "Nice to meet you, $name.\n";

6.
using System;
class Hello {
  static void Main() {
    Console.WriteLine("Please enter your name.\n");
    var name = Console.ReadLine();
    Console.WriteLine("Nice to meet you, " + name + ".\n");
  }
}

7.
name = raw_input("Please enter your name: ")
print "Nice to meet you, ", name, "."

8.
importPackage(java.util);
scanner = new Scanner(System['in']);
System.out.println("Please enter your name.");
name = scanner.nextLine();
System.out.println("Nice to meet you, " + line + ".");

9.
puts "Please enter your name."
name = gets.chomp
puts "Nice to meet you, " + name

10.
main = do
  putStrLn "Please enter your name."
  name <- getLine
  putStrLn ("Nice to meet you, " ++ name ++ ".")

11.
val name = Console.readLine("Please enter your name.")
println("Nice to meet you, " + name + ".")

12.
Name = get_line("Please enter your name.").
put_chars("Nice to meet you, " ++ Name).

Making Methods Testable

I'm going through my old drafts and deleting or publishing them. This one I no longer agree with, I'd rather rewrite the methods to be side-effect free. And the 'magic' I referred to is probably mocks.

"OOP to me means only messaging, local retention and protection and hiding of state-process, and extreme late-binding of all things." -- Alan Kay.

Messaging seems to imply behaviour. From wikipedia: "in object-oriented programming languages such as Smalltalk or Java, a message is sent to an object, specifying a request for action."

It seems fairly trivial that, in, say, Java, Math.cos(double) is not object-oriented. It doesn't take any objects, it doesn't return any objects. Even if double was an object type, it wouldn't be object-oriented. One reason is that it isn't late-bound; the other is that it isn't a message that demands action, it's just a function call.

It's certainly possible to imagine an action that has no effects other than returning a value; I don't dispute that; but it does seem overblown to say "sending the message 'cos' to the Math object", instead of saying that Math has a function called cos, and we're calling that. In fact, function is a much better fit for this, because Math.cos is as close as we can get to a mathematical function. Whenever I say function from now on I'll mean a mathematical function.

Java actually has two implementations of all the maths functions, e.g., Math.cos and StrictMath.cos. We could make it so that which one we used was dynamically configurable (again, I'll cover late binding later), but that doesn't make it any more of an action. It's still a function. I assert that most of what we consider an object's behaviour can be validly and usefully thought of as functions over that object's data. In a simple way, you can see this is true; if an object has state X, and you call method x() on it, that changes the object to be in state Y, and you later return the object to state X and call the method again, it will do the same thing. The big difference between methods and functions seems to be that you can't see what side effects a method causes, without knowing the code.

Methods that have real effects on the world, or change objects, are really actions. Testing these is harder than testing functions. They're also harder to reason about and actually unnecessary.

I can think of two ways of testing them, the standard one of which is to simulate the environment and test for evidence of the action. This has the problem that any unwanted action isn't easily detected, except in the most carefully controlled environments. For example, you might set up a chroot environment for automatically testing a program that manipulates files, and not notice that it erases /etc/passwd (because you never use the chrooted filesystem again), or you might test what a method sends to System.out but neglect to also check System.err.

Another way of testing actions would be to first look at the code differently. Code doesn't do anything. It describes things. A program that writes data to a file doesn't really; it requests that data be written to a file. Intercept all interactions with the outside world. If someone wants to write to System.err, they do it through your testing code. The implementation is a little difficult to conceive; perhaps in Java it has to be done through aspects, or DI, if it is to be reasonably brief.

Once you have all the effects that an action produces, you can see if they match your expectations. There is a complication though; you could end up simulating too much of your environment. If a method asks how big a file is, you need to provide an answer. Ideally you would give a different value for each test, e.g., some exception saying the file is inaccessible, lengths 0, 1, and any other lengths that seem relevant to the method.

What we've actually done is to cocoon the method; we've now made it into a function! The perfect test suite for a method makes the method into a function. Well, that's all well and good for I/O, etc., but how about when we're testing a mutable object - it might have changed more than is usual to test for. E.g.:

public void broken()
{
    setX(5);  // we're happy with this line.
    setY(10); // but this one seems wrong.  We want the test to fail while this line is present.
}
.Let's magically jump in the way and grab a list of changes to the object that this method causes. We know x has been changed and y has been changed, so the test fails. In fact, for this case we never need to execute the actions, because we can see that they fail without executing them. For more interesting cases, we can again simulate the effect. Besides my using this technique to demonstrate a point, it could be used to test real running objects without changing them.

So again, the ideal test suite for a method makes it look like a function. If we adapt our code to explicitly state what effects it should cause, instead of going off and causing them, we then actually have functions in our code. Here's the above broken(), but fixed..

public List<Action> fixed()
{
    return asList(new AssignAction("x",5),new AssignAction("y",10));
}
The code is significantly uglier and doesn't use static typing, but it's now actually a function. Because I've adapted it to return stuff instead of do stuff, it is now far easier to test. Or perhaps all I've done is to make message passing even more explicit. Well, message passing involves actions, and to some extent we can invoke the above actions and observe their results without changing anything (recurse through the list constructing a chain of values, rather like SICP's discussion of chained environments).

It's now clearly far easier to reason about the method, because you can trivially observe all of its side-effects. You could even decide which ones to allow, externally to the code. In the usual case that you want to execute the effects immediately, you can still do that.

Saturday, September 19, 2009

Is it actually type inference we need, or just a better syntax for type declarations?

I've looked a little at Typed Scheme recently, because the main problem I have with Lisp is that it's untyped, but I lack the imagination and skill to make a typed version.

Typed Scheme has local type inference, like C#'s var, but other than that, if you want it typed, you write it typed. The types go before the declarations, like in Haskell, which provoked a surprising thought, namely the title of this post.

In Scala, Java and C#, type inference always seems desirable. Let's look at how you'd declare a method that takes a list, an int and returns an element of that list in each language:

Scala: def method[A](list: List[A], num: Int): A // the : Float would normally be inferred if left out.

Java: A <A> method(List<A> list, int num)

C#: A method<A>(List<A> list, int num)

Those aren't amazingly bad, but compare them to Python:

def method(list, num)

or Scheme:

(define (method the-list num))

The untyped versions are undoubtedly prettier, though far less informative. And compare now to Haskell:

method list num = ...

Haskell's version uses type inference; the types of list and num will be inferred by their usage in the function. But lots of Haskell programmers will write the type explicitly for all functions. I think they do this because in Haskell the syntax for explicit types is better than in Scala, C# and Java:

method :: [a] -> Int -> a
method list num = ...

You can read that first line as "method takes a list of some type we'll call a, an Int and returns an a."

The specific way in which the Haskell (and Typed Scheme) mechanisms are better is that the type information isn't mixed up in the syntax for naming parameters (and after Scala and C# add optional parameters, that too). It'll never happen for any, but I'd like to see the following syntaxes become possible:

Scala:
method[A] : (List[A], Int) => A
def method(list, num) ..

Java/C#:
A method<A> (List<A>, int)
method(list, num) { .. }

The programming language I'll one day write currently looks a bit like Typed Scheme. Like Typed Scheme, it has local variable type inference, but not function definition type inference. I realise that supporting one but not the other is a bit inconsistent, so I know I have more thinking to do, but Typed Scheme (and Haskell) made me realise not to imitate Scala, C# or Java's type declaration syntax.

Friday, January 16, 2009

Victor James Clarkson De Luca, Version 1.0

After 9 months of hard work and alcohol avoidance, Josefina and I are proud to announce that we have managed a stable release of Victor James Clarkson De Luca. Version 1.0 was released on January 5th 2009, before you got to work.

There are no known bugs, as yet. Here's a screenshot:

Friday, January 02, 2009

The Typeclass Pattern

The Typeclass Pattern

This pattern applies to C# and Java, and possibly some other typed languages. It doesn't apply to C++, which does generics via templates.

A simple problem to demonstrate it with is a generic Pythagoras method that takes two numbers a and b and computes sqrt(a * a + b * b) for them. In both C# and Java this can't be written in the most straightforward way:

public T Pythagoras<T>(T a, T b)
{
    return Math.sqrt(a * a + b * b);
}
There's more than one reason, but the 'innermost' is that T doesn't have the operator *, and there's no way to restrict T so that it does.

The equivalent C++ will work, because C++ generates code rather than using constraints.

So the missing information in Pythagoras is:

   * How to multiply two Ts. (let's assume T * T gives T)

   * How to add two Ts. (let's assume T + T gives T)

   * How to find the square root of a T.


interface Num<T>
{
    T Add(T one, T two);
    T Multiply(T one, T two);
    T Sqrt(T t);
}
Now Pythagoras can be written with an extra parameter, a Num:
public T Pythagoras<T>(T a, T b, Num<T> num)
{
    return num.Sqrt(num.Add(num.Multiply(a, a), num.Multiply(b, b)));
}
Clearly, some language support wouldn't go amiss for this, at least in the arithmetic case. What's more of a problem is that your method gets a 'surprising' extra parameter, the Num. It's one of those things that makes sense in isolation, but is really an unnecessary detail when reading the code to gain an understanding of it. Scala offers an interesting solution to that.

In Scala, you might write Pythagoras as:

def pythagoras[T](a: T, b: T)(implicit num: Num[T]) = num.sqrt(num.add(num.multiply(a, a), num.multiply(b, b)))
Then calling it would look like:
pythagoras(3, 5)
The second parameter list for pythagoras is an 'implicit' parameter list, meaning that in compilation the compiler looks for a Num[T] in scope that it can use for num. You can specify it explicitly, e.g., pythagoras(3, 5)(Num.integer), or you can just import Num.integer at some point.

As with all patterns, though, all it takes is a language to support it directly, and then the pattern disappears from user code. In Haskell, Num is a built in type class and Int, Double, etc. are types that are instances, or members, of Num. +, -, *, / are defined as methods that are part of the Num typeclass. Let's omit the sqrt part for a moment:

Prelude> let pythagorasSquared a b = a * a + b * b
Prelude> pythagorasSquared 3 4
25
Prelude> :type pythagorasSquared
pythagorasSquared :: (Num t) => t -> t -> t
I hope the first two commands I gave to the Haskell interpreter are self-explanatory. The third asks what type pythagorasSquared is. That's like asking what signature a method has.

pythagorasSquared is a function with one type parameter called t. t is an instance, or member, of the Num type class. pythagorasSquared takes two values of this type t, and returns a value of the same type. E.g., given two Doubles it will yield a Double. This usually works internally by passing around a Num implicitly, like in the Scala solution, but can work quite like the C++ code generation way, depending entirely on the compiler.

The reason that I omitted the sqrt is that in Haskell, sqrt is defined on Floating, another type class, rather than Num (giving the sqrt of an Int as an Int is perhaps not useful).

At some point, some readers will have stopped understanding the terms, but if you grasped the concept, this wasn't a waste of time!

Thursday, December 11, 2008

Java Just Died (no closures in Java 7)

So it's confirmed. Despite James Gosling wanting closures, despite 3 working closure prototype compilers, despite every other JVM language supporting closures, Java 7 will not have closures.

while (true)
    print("new Runnable() { public void run() { ")
Frankly, I'm pissed off. I'm sure Java dying will kill the JVM too, ultimately.

In the meantime, there's Scala. But the Java community will probably prefer Groovy, because it has learned from Java that types are hard.

(my source: http://twitter.com/theplanetarium via Ismael Juma)

Sunday, November 23, 2008

Binary Reading and Writing Combinators for Java

Binary4J is a combinator library for reading and writing arbitrary file and stream formats. Comment on it here.

Friday, September 19, 2008

My Scala Coding Style

This was originally a posting to the scala-tools mailing list, in response to someone asking how to make the Eclipse plugin format using braces on the next line and spaces instead of tabs.

I used the braces-on-next-line rule, lining up the { to the previous line rule for years, and tabs and no spaces, for years. I was happy with it. I used an 80-character line length limit, which made coding in a text terminal easy, and tabs equivalent to 8 characters (though the actual tab width didn't really matter as I only used indentation to signify nesting depth, not to line up individual characters). My code was very structured.

If you look at my blog's very early days, you will find a post somewhere saying to avoid anonymous classes in Java. This is exactly the opposite of what I'd say now (now I'd say avoid Java :) ). It dawned on me after a while that the reason I didn't like anonymous classes was that my coding style made them a real pain in the backside to use. Specifically, if you have one anonymous class inside another with the above coding style, you end up splitting most lines of actual code.

Then I learned Lisp.

I realised that my overly structured Java code penalised me for nesting. So nesting must be bad, or the coding style must be bad.

Most human languages are highly recursive - within one sentence you can set up phrases, talk about what would happen in the future, and discuss two possible futures or even possible pasts. Only one language is known of that isn't highly recursive - the Piraha language. In Piraha the culture discourages talking about the future, or any event that you haven't seen personally, or been told about by another. A researcher who lived with them and learned their language tried telling them about Jesus (yes, there are God-botherers in linguistics too). One Piraha asked what Jesus looked like - and when the researcher said he didn't know, as Jesus lived 2,000 years ago, the Piraha wasn't interested anymore. This actually caused the researcher to start questioning his own religion, but that's a little beside the point.

I imagine that if you asked a Piraha to design a computer programming language (or a suitable analogy to one - perhaps they wouldn't be interested in computers), I imagine it would be limited to a nesting level of 2, by virtue of a 25-space tab and an 80-character line limit. And if they invented braces, I'm sure they would be lined up.

This has parallels in our society too. The more fluent amongst us can happily deal with long sentences, discussing multiple futures. The less fluent (perhaps speakers of a foreign language learning English) will generally prefer shorter sentences, discussing only the present.

In summary, pick a coding style that doesn't punish nesting, unless you want to make the language 'unnaturally' statement-orientated. I have taken this to an extreme - I use one space for indentation, and never place opening OR closing parens on their own lines. I think this is a direct result of learning Lisp, but it took a long time after learning Lisp for me to change.

Plus, silly Scala makes putting the brace on the next line fail to parse sometimes anyway.

Wednesday, September 10, 2008

Implementing the Builder pattern in Java without repeating code

When writing some Java wrappers around some CGI requests at work, I began with a normal implementation of the builder design pattern, but when I realised I was going to have to do this for about 50 CGI requests, and some of them were nested (CGI requests with query parameters to be sent on to a further CGI request on another machine), and that many of the parameters had interesting constraints, I realised that while the API might be fine, the implementation we were looking at, Josh Bloch's, encouraged repetition of logic.

Anyway, here's an example to get us started. The problem:

Person person = new Person("John", "Jackson", 1979, 11, 10, "AC2193");
We wanted something more like:
Person person = new Person.Builder()
    .forename("John")
    .surname("Jackson")
    .yearOfBirth(1979)
    .monthOfBirth(11)
    .dateOfBirth(10)
    .nationalInsuranceNumber("AC2193").build();
To keep the code short, we'll use a simpler class as an example, a Person consisting of name and age. As you'll see, even this can be large enough to be interesting.
public class Person
{
    private final String name;
    private final int age;

    private Person(Builder builder)
    {
        this.builder = builder;
    }

    public static class Builder
    {
        private String name;
        private int age;

        public Builder name(String name)
        {
            this.name = name;
            return this;
        }

        public Builder age(int age)
        {
            this.age = age;
            return this;
        }

        public Person build()
        {
            return new Person(this);
        }
    }

    public String getName()
    {
        return name;
    }

    public int getAge()
    {
        return age;
    }
}
Even for 2 parameters, this is quite a lot of code, though thus far there isn't really any logic to be duplciated. Now let's look at a really simple constraint, that values cannot be set twice.

The most obvious way of trying this would be to have a boolean alongside each field in the builder, e.g.:

private String name;
private boolean nameAlreadySet;

private int age;
private boolean ageAlreadySet;
And then in the name(String) and age(int) methods in the Builder you would check the value of that boolean, and throw an IllegalStateException if the boolean had already been set. This is clearly a repetition, which can lead to copy-and-paste errors or just make things hard to change.

In object-orientated programming the usual way of handling this would be to package the field with its boolean in an object and call it, say, MaxOnce. There is a good reason not to go down this path, though, it's difficult to chain MaxOnce with other such types, for example when we want BoundedInt, which prevents values outside a certain range, to work with MaxOnce. So we have a problem that the classes don't work together well. Time for another approach.

It would help if MaxOnce and BoundedInt were more like filters that data gets passed through (or not, if the data is invalid). Enter Parameter.

private final Parameter<String> name = maxOnce("name", null);

private final Parameter<Integer> age = bound(maxOnce("age", 0), 0, Integer.MAX_VALUE);
Notice how bound and maxOnce are chained together in the age parameter It's easy to see how you might write other filters. Here's a largely useless example:
Parameter<Integer> number = not(5, bound(maxOnce(0, "a number from one to ten, but not five"), 1, 10));
For a Parameter that has no default, it might be handy to store the value as an Option, rather than use null, or an empty String or some other sentinel. In another case we want to store the value as a TreeMap (for sparse arrays, mentioned later). So generally we'd like to be able to specify an input type and an output type for a Parameter.
private final Parameter<String, Option<String>> name = maxOnce("name");

private final Parameter<Integer, Option<Integer>> age = bound(maxOnce("age"), 0, Integer.MAX_VALUE);
Note that bound and maxOnce work together for the age parameter, as two filters.

In a few cases, the Parameters that we use are allowed to take multiple indexed values. They are effectively sparse arrays. The Parameter's input type is a Pair<Integer, T> and the output type is a TreeMap<Integer, T> - each incoming Pair gets added to the TreeMap.

private final Parameter<Pair<Integer, String>, TreeMap<Integer, String>> = ...;
We can see that the Parameter is more a declaration than it is an actual value. Then it's quite handy that, actually, Parameter holds no mutable state - we store that in a Map<Parameter, Object> but with slightly better types, wrapped up as a GenericBuilder, and we don't modify that Map, we copy it when we add values, like CopyOnWriteArrayList does in the Java libraries.

Here's the original Person class with a new implementation:

public class Person
{
    private final GenericBuilder finalValues;

    private static final Parameter<String, Option<String>> nameParam = param("name", "The name of the person", Conversion.<String>identity());

    private static final Parameter<Integer, Option<Integer>> ageParam = notNegative(param("age", "The age of the person", Conversion.stringToInt));

    private Person(GenericBuilder finalValues)
    {
        if (realBuider.isDefault(nameParam) || realBuilder.isDefault(ageParam))
            throw new IllegalStateException();

        this.finalValues = finalValues;
    }

    public static final class Builder
    {
        private GenericBuilder realBuilder = new GenericBuilder();

        public Builder name(String name)
        {
            realBuilder = realBuilder.with(nameParam, name);
            return this;
        }

        public Builder age(int age)
        {
            realBuilder = realBuilder.with(ageParam, age);
            return this;
        }

        public Person build()
        {
            return new Person(realBuilder);
        }
    }
      
    public String getName()
    {
        return finalValues.get(nameParam);
    }

    public int getAge()
    {
        return finalValues.get(ageParam);
    }
}
There are a couple of extra bells and whistles in the real code, such as building and parsing URLs containing the parameters. I have another post taking this one step further (using Parameters from code generation) in the pipeline.

Sunday, September 07, 2008

An IRC Bot in Haskell, 20% code, 80% GRR

I decided to look at Haskell more seriously, after mainly using it to learn functional programming and, well, as a posh calculator. So when I came across Don Stewart's little tutorial on writing an IRC bot, I followed it, but with one use case in mind:

In the #scala channel, often it's handy to display a URL to a bug by its index, particularly as the URLs are a little tricky to remember.

Don's code was excellent, very readable, and on my little Asus EEE, all I had to do besides install ghc6 was to install ghc6-network-dev - for some reason the Xandros packages are quite split up.

All worked fine - I tested it in a private channel, then I wanted to make it work on a remote machine, which Eugene Ciurana lets me use. Eugene is mainly a Java programmer, so he doesn't have Haskell installed at all, and as I write this, it's around 9am on a Sunday his time - I'm not going to bother him!

So I wondered about installing ghc as a user, and downloaded the 64-bit binary distribution for ghc-6.8.3. After extracting it I realised I couldn't see a bin/ directory or similar, so I checked the README file, which pointed me at the INSTALL file. So I typed ./configure --prefix=/home/ricky/ghc/, only to find out that gcc was broken on the machine.

Eugene also lets me use another machine, a 32-bit one, but on there I got this error from ./configure:

"checking for path to top of build tree... utils/pwd/pwd: /lib/i686/libc.so.6: version `GLIBC_2.3' not found (required by utils/pwd/pwd)"

dmwit and Heffalump (no, really) from #haskell suggested I try using ghc 6.8.2 instead of 6.8.3, which I am going to try shortly, but I thought of another solution. My little Asus EEE runs ghc (albeit version 6.6) well enough, so I compiled my file. After using gcc on and off for years, I was surprised that ghc 3.hs didn't do anything useful - #haskell suggested ghc --make 3.hs. This produced an executable file called 3, which I promptly ssh'd to both of Eugene's machines. On both it failed because libgmp wasn't present. So I was advised to try ghc --make 3.hs -optl-static - which seemed to almost kill my EEE. But a minute and a half later my EEE returned to its usual speed, last.fm started playing again, and I had a somewhat larger file called 3, which worked on the target machine!

So, if you wander into #scala now and type ~trac 100 it will give you a link to Scala bug report 100.

I spent more than 4 times as long on the config as I did on writing (well, mainly copying, though I copied without a clipboard) the code. Hopefully that will drop next time!

Monday, July 28, 2008

Optional Values in Java

If you take some Java code and write psuedocode representing it, you'll probably find that you don't bother with null checks and you don't bother with getters and setters. Sure, in psuedocode you're lazy, but it's more than that - null is usually wrong, so much so that intentional uses of null look like sloppy code.

In fact, if you're writing an API, you probably want to keep null out of your interactions with your users - you want to make sure they realise their mistake if they give you null and you don't want to give them null, lest they forget to check it. But there are actual times when you need some way of representing an optional value.

One particularly popular approach is to use sentinel values - let's say "" for Strings, Double.NaN for doubles, -1 for ints. Now everywhere you read the value you need to check for the sentinel, or be sure that not checking for it won't cause you problems.

Another approach is to use an empty list to represent no value, and a list of 1 element otherwise. Again you need to check whether the list is empty before getting the result out.

You could make a class that might hold a value, that has methods called hasValue() and getValue(). Again, requires a check.

In all these you need to remember to check before you get the value - not much of an improvement over using null directly.

If I categorise some code including null checks (no, not nunchucks), then we'll have something to toy with:

1. foreach

if (x != null) {
 doStuffWith(x);
}
2. map
String s;
if (x == null) {
 s = null;
}
else {
 s = x.toString();
}
3. fold
int length;
if (s == null) {
 length = 0;
}
else {
 length = s.length();
}
Those were some strange names I gave to these categories! Let's tackle foreach first: Think of a value that might be null as a collection containing 0 or 1 elements - foreach would be a loop that runs 0 or 1 times to do something with the value.

map is a mapping from a domain containing null, to a co-domain containing null, - for example, mapping from rectangular coordinates to polar coordinates should probably yield null for a null input, if it doesn't throw an exception.

fold is a more manageable name for a 'catamorphism', which is a transformation that tends to yield a simpler value than the collection it's applied to (which seems the opposite of a fold in origami). In the case of a possibly-null value, the result is simpler because the result is (usually) a not null value.

Being responsible non-repetitive Java programmers, we'd like to encapsulate our possibly-null value plus the checks into an object with three methods, foreach, map and fold, rather than repeating them everywhere:

interface Optional<T> {
 void foreach(Task<T> task);
  R map(Conversion<T,R> conversion);
  R fold(R theDefault, Conversion<T,R> conversion);
}
(you might really want to make Optional Iterable so that you get Java's foreach loop, rather than providing foreach, as an implementation detail).

In the same way that java.util.Collections.sort can take a Comparator, each of these methods takes in an object that has a method that gets called if and when it needs to be.

interface Task<T> { void execute(T value); }
interface Conversion<T,R> { R convert(T value); }
Let's look at how we can convert the earlier null-using code to code using Optional.

1. foreach

x.foreach(doStuff);
2. map
String s=x.map(toString);
3. fold
int length=x.fold(0,length);
Of course, the likelihood is that you're not lucky enough to already have doStuff stored as a Task, toString stored as a Conversion and length stored as a Conversion, so perhaps you'd use an anonymous class to provide those. Unfortunately the syntax for anonymous classes bloats the code too much to be readable in a blog (or an IDE).

It would be useful to have good syntax for using foreach, map and fold in Java, so that there was at last an attractive alternative to null. For now we'll have to settle for attractive semantics rather than attractive syntax though.

I think this is beautiful because it provides a level of abstraction that gets you further from a potential source of bugs, makes your code more expressive about what it accepts, and lets you do in objects what otherwise would be repetitive.

A complete implementation of Optional is available in Functional Java under the name Option. There, Task is called E, and Conversion is called F. Option is most widely known as Maybe, from Haskell.

May your nulls rest in peace.

Monday, July 21, 2008

Designing an Object

If there may exist an object with a method that is not appropriate at all points in the existence of the object, then the object or the method are flawed.

A class encapsulating a compile phase in an IDE might have a blocking or non-blocking execute() method, plus a getErrorMessages(). There is an obvious protocol in using this class - instantiate, call execute(), call getErrorMessages(). It's not particularly hard to use, though it's also not hard to get wrong. Even if you decide not to help those users who don't bother to learn the protocol, it's worth thinking about whether that protocol should even exist, and what the alternative is.

Many readers would probably, when prompted at least, make execute() return the error messages (or a Future for them), which solves the problem quite well. If you wouldn't, keep adding phases plus methods only appropriate for each phase, to one class that grows and grows, until you end up agreeing or changing career :) Anyway, in this case it's clear that the object was flawed by doing two things one after the other - executing the compile phase and delivering results.

I bet most people could train themselves to spot this flaw and remove it, and if anyone only goes that far as a result of reading this post I'll be happy. But most people are probably quite happy with another flaw, java.util.Iterator.next(), which is only allowed when hasNext() returns true, in most Iterator implementations. But moving next() or hasNext() onto another object doesn't really work for Iterator. For a long time I was unhappy with Iterator, but didn't really have a solution, despite trying a couple of things out.

The biggest use of Iterator directly in Java for many years was in what has since been replaced by a foreach loop. There are some detractors of, well, anything new, but generally the foreach loop was really well received by the Java community. It provides a higher-level interface than the Iterator gives us. We can write a lot of code using the foreach loop that would have been more verbose and awkward to get right using Iterator directly. But foreach is only one abstraction; there are some more that are higher still than it, and don't (but can) depend on Iterator. If you don't know what those abstractions are I really think you should take the time to learn about map, filter and reduce, and the more general but less usable parent of those, fold. But this isn't a post about those, so I'll return to the topic at hand.

Iterator has been shown to be flawed, though flawed in a way that is acceptable to most of us and in a way we're used to, and in a way that seems non-trivial to solve (without knowing about map, filter, reduce and fold!). You might not be in a position to, or even want to, replace Iterator, but at least you should know not to copy its design, or bind yourself unnecessarily to it. You're now either armed with a simple way of deciding between two API designs, or you're about to tell me why I'm wrong.

Happy coding.

Thursday, June 26, 2008

Programming in a natural order

Whenever I'm doing the same thing over and over, a little background thread in my brain starts to wonder if there's a better way. Sometimes I tell it to shut up and let me code, other times I listen. In this case it took me a long time to listen, so it must have been pretty persistent. The first time I noticed it was while writing some lisp. Here goes the usual overly trivial example:

I write (+ 3 4) then realise I want to multiply the result by 5. I have to go back to the start of the expression and change it to (* (+ 3 4) 5). I could easily blame lisp's prefix syntax and maybe define some reader macro so I can write something like (+ 3 4) >> (* 5). But that would solve one case and not really fix the overall problem. Here's the obligatory less trivial example:

I write (+ 3 x) then realise that x needs to be a lambda parameter, so I go back and write (lambda (x) (+ 3 x)). I think it's difficult to make the above >> reader macro work with this.
(+ 3 x) >> (lambda (x)) might work, but it's starting to get hard to read. It doesn't seem as natural as it did for the previous case.

But, as I said, it took me a long time to take notice of this background thread, and in fact when I did I was writing Scala, not lisp. When in lisp I just wrote the code anyway, and it didn't harm me noticably. I never wrote the above reader macro, and as I've never written one, chances are it's unwritable anyway.

The case when writing Scala was where I was looking at an expression, then realised that one of its inputs would be a collection, not a single value. A closer-to-reality example - you have a Client, and a Client has a manager, the contact there that you speak with. So you have:
def sendSpam(client: Client) = emailer.send(marketingTripe, client.manager.emailAddress). Then later you change Client.manager to Client.managers, and change its type from Manager to Iterable[Manager]. Now the emailer protests (at compile time), so you have some options:

1. Change the emailer to make it accept an Iterable[Client]. This is actually quite reasonable, and what I did in the real code this mimics.

2. Change the code to:
client.managers foreach (manager => emailer.send(marketingTripe, manager.emailAddress)).

3. Listen to the background thread in your brain, and blog about an automatic transform from the original version to option 2. Today I'm choosing option 3, as you can tell. To avoid ambiguity, I'll introduce some syntax to put around 'managers':
emailer.send(marketingTripe, ^(managers).emailAddress) will be transformed to the code from option 2 above (though perhaps without a real variable name).

At this point, you might be seriously glad that I am not a committer on the compiler for the language that you use every day. But I think the above might actually be a good idea, and might even be a better syntax for a map with a lambda than what we're used to. The reasoning is: it's preferable to write code in a natural order, rather than the order that the language forces you to.

Wednesday, June 25, 2008

A Cross-Language Generics Trick - Java, Scala and C#

Given a Pair<T, U> type in Java, Scala or C#, such as Map.Entry, Tuple2 or KeyValuePair respectively, you can construct type-checked variadic heterogenous containers that you can write general methods to operate on.

Let's write a Pair interface for Java and C#:

interface Pair<T, U> {
 T _1();
 U _2(); }
For Scala we'll use Tuple2, which has _1 and _2 as well. You could use Map.Entry and KeyValuePair in Java and C# respectively, but they seem to have extra semantic information in their names. I know some readers will be crying out for more semantic information than _1 and _2, but I hope they bear with me a moment.

Eliding the implementation, one could have a line of code like the following easily:

Java: Pair<String, Integer> pair = Pairs.pair("hello", 5);
Scala: val pair=("hello", 5)
C#: val pair = Pairs.Pair("hello", 5);
I expect that's fine with most people. For C# you'd probably change 'pair' to 'Pair' for the method name. Then, to start introducing the trick:
Java: Pair<Double, Pair<String, Integer>> withDouble = Pairs.pair(3.0, pair);
Scala: val withDouble = (3.0, pair)
C#: var withDouble = Pairs.Pair(3.0, pair);
You can see that the type in the Java code starts to look a little messy; this is no accident. Explicit static typing makes us more likely to choose less expressive types. Anyway, we can add a method 'prepend' to the Pair type, which doesn't modify anything, but returns a new Pair consisting of a data item on the left and the original Pair on the right. So we get:
Java: Pair<Double, Pair<String, Integer>> pair = Pairs.pair("hello", 5).prepend(3.0);
Scala: val pair = Pairs.pair("hello", 5) prepend 3.0
C#: var pair = Pairs.Pair("hello", 5).Prepend(3.0);
So prepend must be an interesting method, because it looks like you can use it to add more type parameters to something. Clearly you can't, I'm just chaining Pairs, but it makes a nice effect. So far not very useful; I'll get to that. First let's implement prepend:
Java:
 public class Pair<T, U> { ...
  public <V> Pair<V, Pair<T, U>> prepend(V v) {
   return pair(v, this); } }
Scala:
 implicit def Tuple2WithPrepend[T, U](tuple: (T, U)) = new {
  def prepend[V](v: V) = (v, tuple) }
C#:
 public class Pair<T, U> { ...
  public Pair<V, Pair<T, U>> Prepend<V>(V v) {
   return pair(v, this); } }
The nice part about this way of building up Pairs is that you can write methods to handle them instead of writing one per Pair arity. Specifically, you could gather up parameters for an immutable class then instantiate it in one go. In fact, that's what I do in a prototype for a JDBC wrapper. To wet the tastebuds (sorry, only Java for this one):
List<QuestionInfo> questions=select(conn).asString("question").asString("correct").asString("wrong").as(question).from("questions").toList();
The idea is that the above runs the SQL query: select question, correct, wrong from questions and constructs a QuestionInfo for each result, putting the result into a list.

The surprising thing is probably that there's no reflection or casting going on at all. Each asString (well, after the first one really) builds up more in a chain of generic types, then the .as(question) deconstructs them again. question is actually an F<Pair<String, Pair<String, String>>, QuestionInfo>, which means it's a function that takes 3 Strings and returns a QuestionInfo, roughly.

The above code comes from a working test case I published here.

It turns out that someone else had this idea way way way before I did, and made something professional out of it, though only some of that appears to be statically type-checked.

I hope that what I've showed here proves useful to you, and if you are my team leader and I pointed you at this page, remember that you saw it on the Internet, it's real, so you have to let me write it in our project.

Saturday, April 26, 2008

So You Like For Loops? Zip It Up!

I've written this little for loop many a time, it finds all duplicates in a sorted list of integers:

List<Integer> nums=Arrays.asList(1,2,2,3,4,6,6,7,8,8);

List<Integer> dups=new ArrayList<Integer>();
int prev=nums.get(0);
for (Integer i: nums.subList(1))
{
    if (prev==i)
        dups.add(i);
    prev=i;
}
Now go and read your email or something, and come back to read just the for loop (and the line above it). You have to trace through time in your head to work out what it does. The code doesn't say what it means, but that's ok, right, because it works.. hmm.

Let's make up a type called Pair<X,Y>, and quickly imagine that List now has this nice method, zip. Here's the above list, zipped with a sublist of it starting from 1.

System.out.println(nums.zip(nums.subList(1)));
output: ArrayList((1,2),(2,2),(2,3),(3,4),(4,6),(6,6),(6,7),(7,8),(8,8));
Can you see how that relates to the original list? I hope so. Given this data, how would you find duplicates? Well, you'd look for any Pairs where the X and Y value are the same, easy. We'll call that zipped list 'zipped', of type List<Pair<Integer, Integer>>:
List<Integer> dups=new ArrayList<Integer>();
for (Pair<Integer, Integer> pair: zipped)
    if (pair.x().equals(pair.y()))
        dups.add(pair.x());
This for loop is a common pattern now, it's a 'collector'. At each iteration we have a/the list of dups, and the current pair. If the current pair has equal elements we modify the list of dups to make it have one more. Really, it seems like it should be a general operation, filter:
List<Integer> dups=zipped.filter(new Predicate<Pair<Integer, Integer>>()
{
    public boolean invoke(Pair<Integer, Integer> pair)
    {
        return pair.x().equals(pair.y());
    }
}).map(new Function<Pair<Integer,Integer>,Integer>()
{
    public Integer invoke(Pair<Integer, Integer> pair)
    {
        return pair.x();
    }
});
It's kind of better but the syntax is getting in the way. Hold up your closure glasses to the screen, or if you don't have any, I've kindly repeated the code but using the proposed Java 7 closures syntax:
List<Integer> dups=zipped.filter( { Pair<Integer, Integer> pair => pair.x().equals(pair.y()) } ).map( { Pair<Integer, Integer> pair => pair.x() } );
I hope that helped you read the previous code. Let's go one step further with these glasses, they are now magically type inference glasses. We don't need to specify the type of 'pair' because it's blindingly obvious from the type of zipped. We don't need to specify the type of dups because it's blindingly obvious from the return type of filter:
val dups=zipped.filter( { pair => pair.x().equals(pair.y()) } ).map( { pair => pair.x() } );
It looks to me like the braces in there are a bit redundant, the () after x and y are just annoying, and .equals is a Java design error that our glasses can correct:
val dups=nums.zip(nums.tail).filter(pair => pair.x==pair.y).map(pair => pair.x)
Und viz zis Scala zee transfurmaschun vill be complete! (parody of a parody)

Update: Thanks to David MacIver, who spotted a mistake, I had to add 'map' to each of the non-for-loop examples, and in updating it, I've stopped short of what might be the Scala norm - in a closure such as (x => x+2), where the closure parameter is only used once, you can write (_+2). So above you'd write blahblahblah.map(_.x) instead of blahblahblah.map(pair => pair.x).

Sunday, March 02, 2008

Implementing OOP in Java

Object-Oriented Programming is all about late binding. Java has some support for it via polymorphism, but it is not as late as it could be. Java makes some attempt to guarantee things statically, e.g., method calls are guaranteed to correspond to an actual method at runtime. This has a couple of implications:

1. Some of the dynamism that languages like Smalltalk, Python, Ruby and Groovy have is lost.

2. In attempting to reach that dynamism, programmers end up doing things like: throw new UnsupportedOperationException, because their interfaces are too big, and having smaller interfaces would increase the number, and hence perceived complexity, of APIs (yes, this really is the reason java.util has 'optional methods' in interfaces).

Static typing, particularly when it's done really well, is incredibly useful. So useful that it can replace lots of unit tests, or even make unit testing even easier to write. It's actually possible to guarantee that code cannot have a runtime error, if you write it with that in mind. However, some code really needs to be dynamic, at least temporarily, because it's being written by an amateur, or needs to be swapped in or out at runtime, or is an idea that might not match up with your language's typesystem just yet. In that kind of code, guaranteeing that there are no errors is actually an anti-goal.

So, let's implement this idea of OOP, in Java. Some languages have a symbol type that is quite appropriate for this, but Java doesn't, so we'll use strings. To avoid annoying namespace collisions, we'll call our Object type Dyn, short for Dynamic. I chose this short name to not distract from the meaning of Dyn-using code. A Dyn is an object that has a method, ap, that takes a String and zero or more Dyns as parameters, and returns a Dyn. (Some conversion methods to Java's static types might be useful too)

public abstract class Dyn
{
    public abstract Dyn ap(String name,Dyn... args);
}
And an implementation, just enough to try it out:
public static final Dyn identity=new Dyn()
{
    public Dyn ap(String name,Dyn... args)
    {
        return this;
    }
};
The above Dyn is a bit silly, whatever message you send to it, it returns itself, and that's all. Here's one that holds a Java int and when the message "sqr" is passed to it, returns a Dyn holding the square of that int:
public static final Dyn squarer(final int i)
{
    return new Dyn()
    {
        public Dyn ap(String name,Dyn... args)
        {
            return name.equals("sqr") ? squarer(i*i) : identity;
        }
    };
}
Here I'm using the identity object to represent an error/missing method, which seems broken, but right now we can't actually observe that because there's no way to print a Dyn or convert it back to a Java object, so it doesn't really matter. I could add a toString() to the implementation to be able to see the results. I could write Rails for it, with all the method_missing goodness involved.

My question to you who have read this far is, if Dyn was made more a part of a static language instead of a clumsily-added library as shown here, would you be tempted away from Ruby et al? Let's, for this post, reserve the [] brackets to say 'in here be dynamic code'; any time we don't want the typechecker to look at our code, we put it in there, so we might write something like: Animal animal=new Dog(); [ animal.woof(); ] You could write all your code between [ and ], and gradually move it outside when you know how to make it type check, hence incrementally getting better reliability and performance (but reduced flexibility).

Note that this isn't the same thing as adding explicit static types to a dynamic program. Good static typing doesn't need explicit types everywhere, thanks to type inference.

Would this be an attractive option? Does such a language already exist?

Blog Archive

About Me

A salsa dancing, DJing programmer from Manchester, England.