maanantai 26. toukokuuta 2008

Why C++ Still Kicks Ass

Take this simple class for three-dimensional vectors with parametrized types:

template <typename T>
clas
s vec3 {
public:
    T x;
    T y;
    T z;

    vec3(T const& x_, T const& y_, T const& z_)
        : x(x_), y(y_), z(z_) {}

    vec3<T> operator + (vec3<T> const& rhs) const {
        return vec3<T>(x + rhs.x, y + rhs.y, z + rhs.z);
    }
};

C# allows type parametrization, but unfortunately it cannot be combined with operator overloading: you cannot tell the compiler that "these 'T' things can be added too". Java doesn't allow type parametrization over base types, or operator overloading for that matter, so it's off even worse.

C++ makes such code possible because it uses latent typing: the type of T is tracked throughout compilation, and if T doesn't support addition, a compile-time error will be issued. However, if things go wrong, this can lead to pretty astonishing compilation errors.

In the next post, I will present a proposal for adding such latent typing for C# and Java, but considerably more easily than in C++.

keskiviikko 16. huhtikuuta 2008

Verbosity of Non-closured Java Violates the Law of Demeter

It is well known that Java programs (at least of the non-closured kind) tend to be rather verbose. Some people actually even prefer this, since it may make program more readable. In this post, however, I will try to show that verbosity isn't just a local issue. Rather, it affects code quality on a larger scale by increasing temptation to bad design - specifically, violating the law of demeter. Take the following simple Person class:

class Person {
    String name;
    int age;
}


Now assume we have a method containsName:

boolean containsName(List<Person> list, String name) {
    for(Person p : list) {
        if(name.equals(p.name)) {
            return true;
        }
    }
    return false;
}

Notice that the method is only interested in the names of the persons, so its dependency on class Person is merely accidental, unless we anticipate containsName to later utilize other details of class Person. In other words, methods like containsName tend to violate the law of demeter since they need to access the (sub(sub(sub)))fields of their arguments. This results in dreaded "train code", e.g., getInstance().getCompany().getPersons().first().getName().

Here's the version without the dependency:

boolean contains(List<String> xs, String y) {
    for(String x : xs) {
        if(x.equals(y)) {
            return true;
        }
    }
    return false;
}

Such contains method is actually already included in List, so the above method is redundant. However, calling this method is a nightmare since we must "extract" the names of the Persons manually:

List<String> names = new ArrayList();
for(Person p : persons) {
    names.add(p.name);
}
contains(names, "Mikko");

To summarize: the hardness of extracting container fields results in temptation to use less verbose code that violates the law of demeter.

Luckily, with closures, the above will become clearer:

contains(persons.map({Person p => p.name}), "Mikko")

or, equivalently

persons.map({Person p => p.name}).contains("Mikko")

To preserve performance, introducing another method taking a key closure
is warranted:

persons.find({Person p => p.name}, "Mikko")

torstai 20. maaliskuuta 2008

Obtaining BGGA Closure Parameter Types at Runtime

Recently Alex Miller has explored the use of BGGA closures for building dynamic visitors. Such visitor builders, and also Ricky Clarkson's closure-based pattern matcher, could be greatly simplified if we could obtain the parameter types of the closures at runtime. More precisely, given a closure {T => void}, where T is a parameterized type, we are interested in knowing the class of T.

Since Java generics are implemented via erasure, the generic parameter types can easily be lost. Some ways of "manually" reifying the types include:

  • Passing around class literals, e.g., String.class and Integer.class.

  • Subclassing a generic class with specified parameter types. The parameter types can then be read off using getGenericSuperclass method of the associated class object. This is the famed Gafter's gadget.
However, in the case of BGGA closures, the information about parameter types is already present and needs no manual reification. There are at least two ways to obtain it:

  • Using reflection to read the type parameters of the invoke method of the closure. In the current (2008-02-26) BGGA prototype, the invoke method is always the first method in the array returned by getMethods of the closure's class object, which simplifies the implementation.

  • Using the getGenericInterfaces of the closure's class object. BGGA closures implement generic interfaces from package javax.lang.function, and the type parameters can be read out similarly as with Gafter's gadget.
Below is an example of the first method. The second method is probably too brittle given its high reliance on the current implementation of the BGGA prototype.

import java.util.Map;
import java.util.HashMap;

class Visitor<T> {
    private final Map<Class,Object> cases = new HashMap<Class,Object>();

    static <T> Visitor<T> make() {
        return new Visitor<T>();
    }

    <U extends T> Visitor<T> add({U => void} block) {
        Class argClass = block
            .getClass()
            .getMethods()[0] // invoke
            .getParameterTypes()[0];

        cases.put(argClass, block);

        return this;
    }

    @SuppressWarnings("unchecked")
    void visit(T arg) {
        Class argClass = arg.getClass();

        {Object => void} block = ({Object => void}) cases.get(argClass);

        if(block != null) {
            block.invoke(arg);
        }
    }

    public static void main(String[] args) {
        Visitor<Object> v = Visitor.make()
            .add({String s => 
                System.out.println("Mm, I love strings!");})
            .add({Integer i => 
                System.out.println("An Integer is fine too");});

        v.visit("Mikko");
        v.visit(24);
    }
}