Skip to main content

Functional objects made even easier with tiger

Posted by alexwinston on January 20, 2005 at 3:02 PM PST

As a followup to my initial post I have included generics within Predicate(s) to make them virtually resistent to ClassCastException(s). After some additional experimentation with the ideas that I presented in my initial blog I noticed that it was quite easy to create situations in which ClassCastException(s) were possible.

For example the following modifcation caused this situation.

foreach(C.class.getInterfaces(), isProtected, addMethod);

Unfortunlatey the Predicate isProtected is typed to accept Method(s) however because the static Preposition methods are not typed this is not caught by the compiler.

In order to remedy this problem the following refactorings were introduced to eliminate this problem.

public class Preposition {
    public static <T> void with(T subject, Closure<T> c) {
        c.execute(subject);
    }

    public static <T> void when(T subject, Predicate<T> p, Closure<T> c) {
        if (p.evaluate(subject))
            Preposition.with(subject, c);
    }

    public static <T> void foreach(T[] subjects, Closure<T> c) {
        for (T subject : subjects) {
            Preposition.with(subject, c);
        }
    }

    public static <T> void foreach(T[] subjects, Predicate<T> p, Closure<T> c) {
        for (T subject : subjects) {
            Preposition.when(subject, p, c);
        }
    }

    public static <T> void foreach(Collection<T> subjects, Closure<T> c) {
        for (T subject : subjects) {
            Preposition.with(subject, c);
        }
    }

    public static <T> void foreach(
            Collection<T> subjects, Predicate<T> p, Closure<T> c) {
        for (T subject : subjects) {
            Preposition.when(subject, p, c);
        }
    }
}

You will notice that each static method is typed by the subject(s). This ensures that the case previously illustrated is now caught at compile time. This just shows how powerful generics can be in situations like this. Just imagine the possibility of ClassCastExceptions without generics. Thank you tiger!

Related Topics >>