<?xml version="1.0" encoding="utf-8"?>
<feed version="0.3" xmlns="http://purl.org/atom/ns#" xmlns:dc="http://purl.org/dc/elements/1.1/" xml:lang="en">
<title>Alex Winston&apos;s Blog</title>
<link rel="alternate" type="text/html" href="http://weblogs.java.net/blog/alexwinston/" />
<modified>2008-02-27T21:21:50Z</modified>
<tagline></tagline>
<id>tag:weblogs.java.net,2008:/blog/alexwinston/212</id>
<generator url="http://www.movabletype.org/" version="3.01D">Movable Type</generator>
<copyright>Copyright (c) 2008, alexwinston</copyright>
<entry>
<title>Closure Syntax</title>
<link rel="alternate" type="text/html" href="http://weblogs.java.net/blog/alexwinston/archive/2008/02/closure_syntax_1.html" />
<modified>2008-02-27T21:21:50Z</modified>
<issued>2008-02-27T19:00:13Z</issued>
<id>tag:weblogs.java.net,2008:/blog/alexwinston/212.9278</id>
<created>2008-02-27T19:00:13Z</created>
<summary type="text/plain">I appreciate the effort put forth in both the BGGA and FCM proposals to add closures to the Java language but I have a concern regarding the apparent disregard for a syntax that is within the spirit of the language.</summary>
<author>
<name>alexwinston</name>

<email>alex.winston@gmail.com</email>
</author>
<dc:subject>Programming</dc:subject>
<content type="text/html" mode="escaped" xml:lang="en" xml:base="http://weblogs.java.net/blog/alexwinston/">
<![CDATA[<b>I would like to preface this entry with the fact that I am not suggesting a concrete syntax in the examples below.  I am merely using the examples as talking points and illustrations of what I consider to be the "syntactical spirit" of the Java language.</b><br>
<br>
I will be the first to admit that syntax is quite subjective and typically creates consternation within the context of programming specifically.  However, there is also what could be considered the "syntactical spirit" of a language and in this regard I feel that BGGA and FCM have ostensibly missed the mark.<br>
<br>
The most concerning illustration of this is from the FCM proposal itself, "Finally, it should be borne in mind that the syntax is relatively unimportant - the semantics of the proposal are what really matter".  This statement in my opinion is one reason the Java community has been adverse to embrace the proposed changes.  Inherently people are averse to change but if change is inevitable it should be familiar.  Syntax is very important and can in some ways inhibit or foster the use of new functionality and to suggest that either proposal is familiar or similar to Java in most regards would be dubious at best.<br>
<br>
I would like to state the fact that I do not take issue with the semantics of either proposal simply the syntax of each.  That being said let me provide examples from each proposal.<br>
<br>
<b>BGGA</b><br>
<br>
<pre>
    {int=>int} plus2 = {int x => x+2};
</pre>
<br>
I would like to ask honestly who in there right mind thinks this is consistent within any stretch of the imagination with the spirit of the Java language?  Yes Java is verbose, yes it can be cumbersome, but it is not this.  Now I am not going to purport to know the best syntax but wouldn't something like the following be more in line with the Java language?<br>
<br>
<pre>
    int plus2(int) = int (int x) { return x + 2; };
</pre>
<br>
I have read similar statements from a number of individuals within the community and the discussion invariably turns to semantics while overlooking the importance of syntax.<br>
<br>
The following example is even more disturbing.<br>
<br>
<pre>
    public {T => U} converter({=> T} a, {=> U} b, {T => U} c) {  
        return {T t => a.invoke().equals(t) ? b.invoke() : c.invoke(t)};  
    }
</pre>
<br>
Not only that but something like the following appears more terse.<br>
<br>
<pre>
    public &lt;T, U&gt; U converter(T a(), U b(), U c(T)) {
        return (T t) { a().equals(t) ? b() : c(t); };
    }
</pre>
<br>
Again this is just a talking point, and might very well not be syntactically equivalent, but as an avid supporter of the Java language I cannot support the BGGA syntax in any capacity.<br>
<br>
<b>FCM</b><br>
<br>
Unfortunately FCM is not much better, they did put some thought into the syntax but it only makes for a marginally more spirited alignment.<br>
<br>
<pre>
    public class MyClass {
        public void process() {
            (void(String)) example = #(String message) {
                Logger.log(this, message);
            };
            example.invoke("Logged message");
        }
    }
</pre>
<br>
It seems there are unneeded parentheses and calls to invoke.  Something like the following seems more appropriate although less terse.<br>
<br>
<pre>
    public class MyClass {
        public void process() {
            void example(String) =  void (String message) {
                Logger.log(this, message);
            };
            example("Logged message");
        }
    }
</pre>
<br>
One thing I am not sure I understand either is the need for the invoke(...) call.  Is there a particular reason function(...) could not be used over function.invoke(...)?<br>
<br>
All that being said I am not trying to create controversy.  I am merely encouraging a reevaluation of the syntax proposed by both BGGA and FCM.  This, in my opinion, will be as critical to the success of closures as semantics.  It almost seems as though we should refocus BGGA and FCM on the semantics and create competing proposals for the syntax.  I do realize that the syntax of each proposal follows the semantics, form follows function, but that is a moot point until we have something more palatable.]]>

</content>
</entry>
<entry>
<title>Nashville Java Conference Speakers Needed</title>
<link rel="alternate" type="text/html" href="http://weblogs.java.net/blog/alexwinston/archive/2007/05/nashville_java.html" />
<modified>2007-05-30T17:00:51Z</modified>
<issued>2007-05-30T16:29:31Z</issued>
<id>tag:weblogs.java.net,2007:/blog/alexwinston/212.7519</id>
<created>2007-05-30T16:29:31Z</created>
<summary type="text/plain">Java speakers are needed for an upcoming conference, http://devlink.net, in Nashville, Tennessee.</summary>
<author>
<name>alexwinston</name>

<email>alex.winston@gmail.com</email>
</author>
<dc:subject>Community</dc:subject>
<content type="text/html" mode="escaped" xml:lang="en" xml:base="http://weblogs.java.net/blog/alexwinston/">
Java speakers are needed for an upcoming conference, http://devlink.net, in Nashville, Tennessee.  We currently only have 2-3 committed Java speakers and are far outnumbered by .Net speakers.  If you or someone you know would like to speak at a regionally sponsored event please contact me immediately.  The conference is open to presentations on most any topic and we can help in various ways with travel and accommodations.  Please spread this announcement to help promote this conference and bring more awareness to Java technologies in Tennessee and the surrounding areas.  I can be reached at alex.winston at gmail.com.

</content>
</entry>
<entry>
<title>Strongly Typed Java Delegates</title>
<link rel="alternate" type="text/html" href="http://weblogs.java.net/blog/alexwinston/archive/2005/04/strongly_types_1.html" />
<modified>2008-01-02T17:42:16Z</modified>
<issued>2005-04-11T22:54:28Z</issued>
<id>tag:weblogs.java.net,2005:/blog/alexwinston/212.2287</id>
<created>2005-04-11T22:54:28Z</created>
<summary type="text/plain">I have read a large number of articles lately detailing various implementations of sudo delegates in java.  Unfortunately all of them are type unsafe.  I decided to set out to implement type safe java delegates with the help of cglib2.</summary>
<author>
<name>alexwinston</name>

<email>alex.winston@gmail.com</email>
</author>
<dc:subject>Community: Java Patterns</dc:subject>
<content type="text/html" mode="escaped" xml:lang="en" xml:base="http://weblogs.java.net/blog/alexwinston/">
<![CDATA[Weakly typed sudo java delegate implementations seem to be a dime a dozen these days.  After reading the latest article on JDJ http://sys-con.com/story/?storyid=49097&DE=1 about yet another weakly typed implementation for java delegates I decided it was high time to put my brain to work on implementing strongly typed delegates.  With a little imagination and some magic it was quite simple, while also providing a rather elegant solution.<br>
<br>
Unfortunately every implementation that I have seen requires the use of strings to delegate to named methods.  For example the most recent JDJ article utilizes the following syntax.<br>
<br>
<pre>
Delegate delegate = new Delegate(
  System.out, "println");
delegate.invoke("Hello World!");
</pre>
<br>
This is readable but as you are no doubt aware if you mistype the method name then you are out of luck.  It also does not not allow method completion in your favorite IDE.<br>
<br>
As I set out to solve this problem I stumbled upon Micorsoft's implementation of delegates in J++ outlined in Sun's white paper at http://java.sun.com/docs/white/sidebar.html.  As such I attempted to model my implementation as closely as I could to the example provided because it provided a starting point for envisioning a possible solution.<br>
<br>
<pre>
delegate long IntOp(int a, int b);

public class Example {
    long add(int a, int b) {
        return a + b;
    }

    public long doIt() {
        IntOp op = new IntOp(this.add);
        long result = op.invoke(2, 3);

        return retult;
    }
}
</pre>
<br>
Several points should be made, because delegates are method pointers you must call invoke(...) to execute the delegate.  In my opinion you lose some readability utilizing this method because it is difficult to identify that you are actually invoking add(int a, int b).  Additionally it appears that a cast may be required upon invocation of the delegate in order to store the result.  I did not test the above code so I am not cartain.<br>
<br>
In light of this I dreamt up the following code fragment which would provide type safety as well as providing the ability to invoke the delegate method by name instead of an equivalent invoke(...) method.<br>
<br>
<pre>
abstract class IntOp { abstract long add(int a, int b); }

public abstract class Example {
    abstract IntOp add();
    public long add(Integer a, Integer b) {
        return a + b;
    }

    public static long doIt() throws Exception {
        IntOp op = delegate(Example.class).add();
        long result = op.add(2, 3);

        return result;
    }
}
</pre>
<br>
Several observations.  The code fragment is only one line longer than the equivalent J++ example.  Additionally the delegate keyword obviously does not exist so an abstract class was used instead for IntOp.  The only additional difference is the addition of the "abstract IntOp add()" method.  As I begin to further explain this example below it will become apparent that this method is the key to allowing type safety.<br>
<br>
All of the magic obviously happens in the static delegate method.  It accepts a class and returns an object instance.  This allows for the ability to implement the "abstract IntOp add()" method such that it creates an IntOp proxy object.  The proxied object in turn delegates to a matching method signature in the Example class with the given arguments.  This is a very simple approach.  A more elegant solution would provide some sort of Handler that would allow the delegation to differently named methods, but nontheless this is a good starting point.  Thus the "abstract IntOp add()" method could be read to mean, provide a delegate of type IntOp which delegates the add method.<br>
<br>
In order to proxy the object like this I turned to cglib2 because the Proxy facility in java makes this a bit too complex.<br>
<br>
The implementation of the delegate method follows.<br>
<br>
<pre>
public class Delegate {
    public static <T> T delegate(T t) throws Exception {
        return (T) Delegate.delegate(t.getClass());
    }

    public static <T> T delegate(Class<T> t) throws Exception {
            return (T) Enhancer.create(t, new ProxyInterceptor(t));
    }

    public static class ProxyInterceptor implements MethodInterceptor {
        private Object proxy;

        public ProxyInterceptor(Class delegate) {
            this.proxy = Enhancer.create(delegate, NoOp.INSTANCE);
        }

        public Object intercept(final Object o, final Method m,
                Object[] args, MethodProxy mp) throws Throwable {
            return Enhancer.create(m.getReturnType(),
                new MethodInterceptor() {
                    public Object intercept(Object o1, Method m1,
                            Object[] args1, MethodProxy mp1) throws Throwable {
                        return proxy.getClass().getMethod(
                            m.getName(), classes(args1)).invoke(proxy, args1);
                    }
                });
        }
    }

    private static Class[] classes(Object[] objects) {
        Class[] classes = new Class[objects.length];
        for (int i = 0; i < objects.length; i++)
            classes[i] = objects[i].getClass();
        return classes;
    }
}
</pre>
<br>
I will not attempt to explain the details of this class because it is extremely rough and would require some background in cglib2.  Needless to say it does what we need it to do.<br>
<br>
Having this little trick in our bag now we can utilize delegates in a variety of circumstances which follow with code examples.<br>
<br>
The first example is a modification of the example presented in Microsoft's argument for delegates at http://msdn.microsoft.com/vjsharp/productinfo/visualj/visualj6/technical/articles/general/truth/default.aspx.<br>
<br>
<pre>
public class SimpleFrame extends JFrame
{
    Button buttonOK = new Button();
    JButton buttonReset = new JButton();
    JButton buttonCancel = new JButton();

    public static void main(String[] args) throws Exception {
        SimpleFrame frame = new SimpleFrame();
        frame.initForm();
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.setPreferredSize(new Dimension(100, 100));
        frame.pack();
        frame.setVisible(true);
    }

    void initForm() throws Exception
    {
        buttonOK.setLabel("Ok");
        buttonOK.addActionListener(
            delegate(SimpleFrameHandler.class).ok());

        buttonReset.setText("Reset");
        buttonReset.addActionListener(
            delegate(SimpleFrameHandler.class).reset());

        buttonCancel.setText("Cancel");
        buttonCancel.addActionListener(
            delegate(SimpleFrameHandler.class).cancel());

        this.add(buttonOK, BorderLayout.NORTH);
        this.add(buttonReset, BorderLayout.CENTER);
        this.add(buttonCancel, BorderLayout.SOUTH);
    }


    public abstract class SimpleFrameHandler {
        abstract ActionListener ok();
        public void ok(ActionEvent e)
        {
            System.out.println("Ok clicked");
        }

        abstract ActionListener reset();
        public void reset(ActionEvent e)
        {
            System.out.println("Reset clicked");
        }

        abstract ActionListener cancel();
        public void cancel(ActionEvent e)
        {
            System.out.println("Cancel clicked");
        }
    }
}
</pre>
<br>
As you can no doubt see strongly typed delegates allow us to add ActionListener(s) without the need for anonymous classes.  The modifications actually closely resemble those presented to illustrate the advantages of C# delegates in .Net.  Unfortunately this isn't anything particularly special.  All that is really happening is that the anonymous class is created for you and accessed via the abstract method defining what interface or abstract class to implement and delegate to.  It does however provide a useful abstraction that could be used in more complex situations providing the potential for powerful functionality.<br>
<br>
The last example modifies the code presented in the most recent java.net article http://today.java.net/pub/a/today/2005/04/07/pojostrategy.html outlining uses of the Comparator class.<br>
<br>
<pre>
public abstract class Sort {
    abstract Comparator<String> compareIgnoreCase();
    public int compareIgnoreCase(String s1, String s2) {
        return s1.toLowerCase().compareTo(s2.toLowerCase());
    }

    static String[] alphabeticallyIgnoreCase(String... unsorted) throws Exception {
        String[] sorted = unsorted.clone();
        Arrays.sort(sorted, delegate(Sort.class).compareIgnoreCase());

        return sorted;
    }
}
</pre>
<br>
As you can see the implementation delegates to a type safe case comparison method returned by the proxied Comparator.<br>
<br>
As I attempted to set out to solve type safe delegates in java I initially thought it would be quite difficult but as mentioned, with a little imagination and the magic of cglib2 anything is possible.  Say goodbye to type unsafe delegates.]]>

</content>
</entry>
<entry>
<title>Functional objects made even easier with tiger</title>
<link rel="alternate" type="text/html" href="http://weblogs.java.net/blog/alexwinston/archive/2005/01/functional_obje_1.html" />
<modified>2008-01-02T17:42:16Z</modified>
<issued>2005-01-20T23:02:57Z</issued>
<id>tag:weblogs.java.net,2005:/blog/alexwinston/212.1955</id>
<created>2005-01-20T23:02:57Z</created>
<summary type="text/plain">As a followup to my initial post I have included generics within Predicate(s) to make them virtually resistent to ClassCastException(s).</summary>
<author>
<name>alexwinston</name>

<email>alex.winston@gmail.com</email>
</author>
<dc:subject>Patterns</dc:subject>
<content type="text/html" mode="escaped" xml:lang="en" xml:base="http://weblogs.java.net/blog/alexwinston/">
<![CDATA[<p>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.</p>

<p>For example the following modifcation caused this situation.</p>

<pre>
foreach(C.class.getInterfaces(), isProtected, addMethod);
</pre>

<p>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.</p>

<p>In order to remedy this problem the following refactorings were introduced to eliminate this problem.</p>

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

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

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

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

<p>    public static &lt;T&gt; void foreach(Collection&lt;T&gt; subjects, Closure&lt;T&gt; c) {<br />
        for (T subject : subjects) {<br />
            Preposition.with(subject, c);<br />
        }<br />
    }</p>

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

<p>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!</p>]]>

</content>
</entry>
<entry>
<title>Functional objects made easy with tiger</title>
<link rel="alternate" type="text/html" href="http://weblogs.java.net/blog/alexwinston/archive/2005/01/functional_obje.html" />
<modified>2008-01-02T17:42:16Z</modified>
<issued>2005-01-19T14:49:33Z</issued>
<id>tag:weblogs.java.net,2005:/blog/alexwinston/212.1949</id>
<created>2005-01-19T14:49:33Z</created>
<summary type="text/plain">After reading CrazyBob&apos;s article
about sudo closures in java some time ago I made it a point to familiarize myself
with this particular idiom as well as others that are often talked about but rarely
used within the java community.  Unfortunately some time passed and as most things
this todo slipped my mind until I stumbled upon this article.</summary>
<author>
<name>alexwinston</name>

<email>alex.winston@gmail.com</email>
</author>
<dc:subject>Patterns</dc:subject>
<content type="text/html" mode="escaped" xml:lang="en" xml:base="http://weblogs.java.net/blog/alexwinston/">
<![CDATA[<p>After reading CrazyBob's <a href="http://www.crazybob.org/roller/page/crazybob/20031215#closure_design_pattern">article</a> about sudo closures in java some time ago I made<br />
it a point to familiarize myself with this particular idiom as well as others that<br />
are often talked about but rarely used within the java community.  Unfortunately<br />
some time passed and as most things this todo slipped my mind until I stumbled<br />
upon <a href="http://www.onjava.com/lpt/a/5517">this</a> article.</p>

<p>The article was rather short but provided practical examples of how to use<br />
commons-collections to express functional object constructs within java.  I read<br />
the article with great anticipation and began to explore commons-collections<br />
and even attempted to port CrazyBob's simple example.  This is however where the<br />
difficulty began.  The library seemed a bit awkard and verbose and I found myself<br />
wanting features found in ruby and oft talked about on Brian McCallister's<br />
<a href="http://kasparov.skife.org/blog">blog</a>.  In an attempt to bridge the<br />
gap between languages that offer true functional object support and java I fired<br />
up my trusty ide and set off to find a solution.</p>

<p>I felt that commons-collections abtraction of Predicates and Closures was a start<br />
but something else was missing, not to mention the verbosity of the implementation.<br />
In order to alleviate some of the verbosity I decided to use features provided<br />
in jdk 1.5 and build upon the simple abstractions provided by commons-collections.</p>

<p>Now I do not puport to be an english scholar by any means but when I began to<br />
think somewhat abstractly about predicates and closure sentence structure <br />
began to come to mind.  Specifically I was envisioning the preposition of subjects<br />
for predicates against closures.  That may or may not actually make any meaningful<br />
sense to an english scholar but it made sense in my head and so I set off to<br />
implement it accordingly.</p>

<p>To begin I created interfaces for Predicate(s) and Closure(s) as illustrated below.</p>

<pre>
    public interface Predicate&lt;T&gt; {
        public boolean evaluate(T t);
    }
    
    public interface Closure&lt;T&gt; {
        public void execute(T t);
    }
</pre>

<p>Unfortunately I needed to conceptualize Prepositions and Subjects as mentioned <br />
previously.  As an XPer this is usually where I fire up a test and begin<br />
test first design.  As expected it produced rather good results.  As a starting<br />
point I used the example presented in the article to illustrate the use of commons-collections<br />
as seen below.</p>

<pre>
    public void testPreposition() {
        Predicate&lt;Student&gt; isPassing = new Predicate&lt;Student&gt;() {
            public boolean evaluate(Student s) {
                return ((s.getGrade() == Grade.A || s.getGrade() == Grade.B));
            }
        };

<p>        Predicate&lt;Student&gt; isNotAbsent = new Predicate&lt;Student&gt;() {<br />
            public boolean evaluate(Student s) {<br />
                return s.getDaysAbsent() == 0;<br />
            }<br />
        };</p>

<p>        final List&lt;Student&gt; honorRoll = new ArrayList&lt;Student&gt;();<br />
        Closure&lt;Student&gt; addToHonorRoll = new Closure&lt;Student&gt;() {<br />
            public void execute(Student student) {<br />
                honorRoll.add(student);<br />
            }<br />
        };</p>

<p>        Student student = new Student(Grade.D, 0);</p>

<p>        when(student, isNotAbsent, addToHonorRoll);<br />
        assertEquals(1, honorRoll.size());<br />
        assertEquals(0, honorRoll.get(0).getDaysAbsent());<br />
        honorRoll.clear();</p>

<p>        List&lt;Student&gt; students = Arrays.asList(new Student[] {<br />
        new Student(Grade.A, 1), new Student(Grade.B, 0),<br />
        new Student(Grade.C, 0) });</p>

<p>        foreach(students, isPassing, addToHonorRoll);<br />
        assertEquals(2, honorRoll.size());<br />
        assertEquals(Grade.A, honorRoll.get(0).getGrade());<br />
        assertEquals(Grade.B, honorRoll.get(1).getGrade());<br />
        honorRoll.clear();<br />
    }<br />
</pre></p>

<p>I came to the conclusion that prepositions should be evaluated against subjects,<br />
predicates and closures as illustrated by the following code fragment.</p>

<p>when(student, isNotAbsent, addToHonorRoll);</p>

<p>The preposition would evaluate the subject(student) against the predicate(<br />
isNotAbsent) and execute closure(addToHonorRoll) accordingly.  My first attempt<br />
produced Predicate.when(...) however static imports jumped to mind and provided<br />
a rather elegant, scripty, solution.  Now I am not a fan of static imports but<br />
this felt like an applicable use.  As you will notice I also took advantage of<br />
generics in order to eliminate unneeded casts which in turn creates much more concise<br />
code.</p>

<p>The ability to evaluate Predicate(s) and Closure(s) against a Subject was at hand<br />
however I now needed the ability to evaluate them against multiple Subjects.  This<br />
produced the following implementation of Preposition including the features mentioned<br />
above as well.</p>

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

<p>    public static void when(Object subject, Predicate p, Closure c) {<br />
        if (p.evaluate(subject))<br />
            Preposition.with(subject, c);<br />
    }<br />
    <br />
    public static void foreach(Object[] subjects, Closure c) {<br />
        for (Object subject : subjects) {<br />
            Preposition.with(subject, c);<br />
        }<br />
    }<br />
    <br />
    public static void foreach(Object[] subjects, Predicate p, Closure c) {<br />
        for (Object subject : subjects) {<br />
            Preposition.when(subject, p, c);<br />
        }<br />
    }<br />
    <br />
    public static void foreach(Collection subjects, Closure c) {<br />
        for (Object subject : subjects) {<br />
            Preposition.with(subject, c);<br />
        }<br />
    }<br />
    <br />
    public static void foreach(Collection subjects, Predicate p, Closure c) {<br />
        for (Object subject : subjects) {<br />
            Preposition.when(subject, p, c);<br />
        }<br />
    }<br />
}<br />
</pre></p>

<p>I could now use the following syntax to meet this requirement.</p>

<p>foreach(subjects, isPassing, addToHonorRoll);</p>

<p>This was a great start however as I began to port CrazyBob's example I found <br />
something missing.  First the inability to execute Closure without a Predicate<br />
as well as the ability to nest Predicates.  Fortunately these two problems were<br />
one in the same and were solved by adding the methods above that execute Closure<br />
against a Subject without concern for a Predicate.  The above example includes methods<br />
without Predicates but at the time they did not exist.</p>

<p>This refactoring evolved from the following test which is an attempt to get<br />
various methods from a class or interface much like the example in CrazyBob's<br />
article.</p>

<pre>
    public void testRecursivePreposition() {
        final Predicate&lt;Method&gt; isPublic = new Predicate&lt;Method&gt;() {
            public boolean evaluate(Method m) {
                return Modifier.isPublic(m.getModifiers());
            }
        };

<p>        final Predicate&lt;Method&gt; isProtected = new Predicate&lt;Method&gt;() {<br />
            public boolean evaluate(Method m) {<br />
                return Modifier.isProtected(m.getModifiers());<br />
            }<br />
        };</p>

<p>        final List&lt;Method&gt; methods = new ArrayList&lt;Method&gt;();<br />
        final Closure&lt;Method&gt; addMethod = new Closure&lt;Method&gt;() {<br />
            public void execute(Method m)  {<br />
                    methods.add(m);<br />
            }<br />
        };</p>

<p>        Closure&lt;Class&gt; addMethods = new Closure&lt;Class&gt;() {<br />
            public void execute(Class c)  {<br />
                foreach(c.getDeclaredMethods(), isPublic.or(isProtected), addMethod);<br />
            }<br />
        };</p>

<p>        with(C.class, addMethods);<br />
        assertEquals(4, methods.size());<br />
        assertEquals("getA", methods.get(0).getName());<br />
        assertEquals("getAA", methods.get(1).getName());<br />
        assertEquals("getB", methods.get(2).getName());<br />
        assertEquals("getBB", methods.get(3).getName());<br />
        methods.clear();</p>

<p>        foreach(C.class.getDeclaredMethods(), isProtected, addMethod);<br />
        assertEquals(2, methods.size());<br />
        assertEquals("getAA", methods.get(0).getName());<br />
        assertEquals("getBB", methods.get(1).getName());<br />
        methods.clear();</p>

<p>        foreach(C.class.getInterfaces(), addMethods);<br />
        assertEquals(2, methods.size());<br />
        assertEquals("getA", methods.get(0).getName());<br />
        assertEquals("getB", methods.get(1).getName());<br />
        methods.clear();<br />
    }</p>

<p>    interface A {<br />
    public void getA();<br />
    }</p>

<p>    interface B {<br />
    public void getB();<br />
    }</p>

<p>    class C implements A, B {<br />
        public void getA() { }<br />
        protected void getAA() { }<br />
        private void getAAA() { }</p>

<p>        public void getB() { }<br />
        protected void getBB() { }<br />
        private void getBBB() { }<br />
    }<br />
</pre></p>

<p>You will notice that a foreach is nested within the Closure addMethods which<br />
makes reference to the subject passed via the execute method.  Additionally<br />
you will notice the introduction of isPublic.or(isProtected).  This is a refactoring<br />
of the Predicate class to support conditioning which just shows how these<br />
concepts can be expanded to provide a more robust solution.  The code refactorings<br />
follow.</p>

<pre>
    public abstract class Predicate&lt;T&gt; {
        public abstract boolean evaluate(T t);
    
        public Predicate and(final Predicate p) {
            return Conjunction.and(this, p);
        }
    
        public Predicate or(final Predicate p) {
            return Conjunction.or(this, p);
        }
    }

<p>    public class Conjunction {<br />
        public static Predicate and(final Predicate p1, final Predicate p2) {<br />
            return new Predicate&lt;Object&gt;() {<br />
                public boolean evaluate(Object t) {<br />
                    return p1.evaluate(t) && p2.evaluate(t);<br />
                }<br />
            };<br />
        }</p>

<p>        public static Predicate or(final Predicate p1, final Predicate p2) {<br />
            return new Predicate&lt;Object&gt;() {<br />
                public boolean evaluate(Object t) {<br />
                    return p1.evaluate(t) || p2.evaluate(t);<br />
                }<br />
            };<br />
        }<br />
    }<br />
</pre></p>

<p>Obviously this is a rather simplistic example however it illustrates in my opinion very<br />
powerful abstractions and is much cleaner than commons-collection.  You<br />
can even implement this yourself without the need for an external library and evolve<br />
it to meet your needs accordingly.</p>

<p>Unfortunately functional objects will never be fully realized until they<br />
are supported implicitly by the language however with some thought and<br />
clever use of 1.5 constructs this is now more a reality than ever before.</p>

<p>On an unrelated note if someone knows why mozilla double spaces the code examples please post a comment.</p>]]>

</content>
</entry>

</feed>