The Source for Java Technology Collaboration
User: Password:



Alex Winston's Blog

Functional objects made even easier with tiger

Posted by alexwinston on January 20, 2005 at 03:02 PM | Comments (1)

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!


Bookmark blog post: del.icio.us del.icio.us Digg Digg DZone DZone Furl Furl Reddit Reddit
Comments
Comments are listed in date ascending order (oldest first) | Post Comment

  • for flexibility, would you want to do <? super T> on both the Predicate and Closure within each method signature? I believe this would then allow foreach(AccountImpl[], Predicate<Account>, Closure<Account>)

    Posted by: jhook on January 20, 2005 at 03:47 PM





Powered by
Movable Type 3.01D
 Feed java.net RSS Feeds