<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet href="/stylesheets/rss.css" type="text/css"?>
<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/">
  <channel>
    <title>Just a Thought...: Judicious Use of Closures</title>
    <link>http://bloritsch.d-haven.net/articles/2007/07/22/judicious-use-of-closures</link>
    <language>en-us</language>
    <ttl>40</ttl>
    <description>Random thoughts</description>
    <item>
      <title>Judicious Use of Closures</title>
      <description>&lt;p&gt;After going back and reviewing some of my old articles, I got to thinking that my role based authorization system I outlined &lt;a href="http://bloritsch.d-haven.net/articles/2006/04/28/role-based-authorization-in-ruby-on-rails"&gt;in this article&lt;/a&gt;  still reflected my Java bias.  I know some people approach new toys and technologies by diving in head first, and then backing off later.  I personally try to think of what problems that approach can practically solve.  As a result I may be a late bloomer, but the flowers are nicer.&lt;/p&gt;


	&lt;p&gt;The whole issue of why I thought it could be better is because it is still too Java/C++ based.  I tried to make it more rubyesque but I stopped short.  You see, in the Java/C++/C# world you think about having to &lt;em&gt;query&lt;/em&gt; an object and then do something.  This is in stark contrast to the Smalltalk and Ruby approach where you &lt;em&gt;tell&lt;/em&gt; an object to do something for you.  You can even pass in some extra steps so that you can be very happy.  So what&amp;#8217;s the difference, and does it really make a big deal?  The difference is subtle, but so is elegance.  Let&amp;#8217;s consider the code I had you write to do work if a user had a particular role:&lt;/p&gt;


&lt;pre&gt;
if @user.is_in_role? (:Admin)
  Article.find(params[:id]).destroy
  flash[:notice] = 'Article was successfully deleted.'
end
&lt;/pre&gt;

	&lt;p&gt;The &amp;#8220;is_in_role?&amp;#8221; message is straight from Java&amp;#8217;s HttpServletRequest interface.  It does make sense from a certain point of view, but the control is inverted from what it should be.  In short, we should &lt;em&gt;tell the user&lt;/em&gt; to do something if they have a roll.  Here&amp;#8217;s how the same logic should look from the subtle shift in viewpoint:&lt;/p&gt;


&lt;pre&gt;
@user.with_role :Admin do
  Article.find(params[:id]).destroy
  flash[:notice] = 'Article was successfully deleted.'
end
&lt;/pre&gt;

	&lt;p&gt;So what&amp;#8217;s the big deal?  They both do the same thing, and they are both pretty readable.  The big fat hairy deal is in perspective.  The first version is interrogative, we are treating the user object like a little child and taking back control.  We aren&amp;#8217;t letting the user object do his part of the chores.  The the second version is imperative, we are telling the user object what we need him to do.  We trust him to make judgments like whether he can do it or not.  The implementation of the method is just about the same under the covers, but the important thing to stress is who is doing what.  We should provide general directions, and the objects should pull their own weight to make it happen.&lt;/p&gt;


	&lt;p&gt;Ruby is really great when it comes to closures.  Every method implicitly handle closures.  The trick is the &lt;code&gt;yield&lt;/code&gt; keyword.  If you want to pass a parameter to the closure, just add it on to the yield command.  Here is how our implementation would look if we did the more rubyesque approach:&lt;/p&gt;


&lt;pre&gt;
def with_role role
  if roles.include? Role[role]
    yield
  end
end
&lt;/pre&gt;

	&lt;p&gt;That&amp;#8217;s pretty slick when you think about it.  You can make any method handle closures just by using the &lt;code&gt;yield&lt;/code&gt; command.  If we needed to pass parameters, we just tack them on after the yield command.  There&amp;#8217;s tons of applications for it, but it&amp;#8217;s best to start off slow.  After you add support for a closure to an object&amp;#8217;s method, ask yourself if it makes life better.  Is the code that matters more readable?  Does it simplify life?  The answers to those questions will help you walk the balance between elegant and gimmicky.&lt;/p&gt;


	&lt;h4&gt;Contrast Ruby With Java&lt;/h4&gt;


	&lt;p&gt;I&amp;#8217;m cheating a little bit with referencing the current specification proposal for &lt;a href="http://www.javac.info/closures-v05.html"&gt;&lt;span class="caps"&gt;JSR&lt;/span&gt; for Closures in Java&lt;/a&gt;  as it represents the closest thing to what you can expect here.  First of all, if you use Ruby or Smalltalk you will be sorely disappointed.  In a sense, Java closures still follow the same pattern in that the closure is an object&amp;#8212;only you have to be explicit about it.  &lt;strong&gt;Edit:&lt;/strong&gt; &lt;em&gt;Apparently I missed a very important, and good part of the new Java closure spec.  I&amp;#8217;m changing the code examples to reflect the preferred method.&lt;/em&gt;&lt;/p&gt;


	&lt;p&gt;First, let&amp;#8217;s look at the Java way of solving the problem we solved with Ruby:&lt;/p&gt;


&lt;pre&gt;
if ( user.isInRole("Admin") ) {
    Article.find(id).destroy();
    sendMessage( "Article was successfully deleted." );
}
&lt;/pre&gt;

	&lt;p&gt;It&amp;#8217;s fairly readable, and it doesn&amp;#8217;t look too bad.  Again, we are treating the user object like a little child.  We are asking the object about itself and assuming control.  The approach has its roots in the procedural world that the C based languages came from.  Now let&amp;#8217;s look at what the new Java Closures will look like, and whether that will help things be more readable.&lt;/p&gt;


&lt;pre&gt;
user.withRole("Admin") {
    Article.find(id).destroy();
    sendMessage( "Article was successfully deleted." );
}
&lt;/pre&gt;

	&lt;p&gt;There is an uglier way of declaring the closure, but since we want the code to be as elegant as possible I chose this form.  Before I go into details of what is going on under the hood, we need to see the other half of the equation so we can better understand what&amp;#8217;s going on.  Here&amp;#8217;s the implementation of the &lt;code&gt;withRole&lt;/code&gt; method:&lt;/p&gt;


&lt;pre&gt;
public void withRole(String role, {=&amp;gt;void} block) {
    if ( roles.contains( role ) ) {
        block.invoke();
    }
}
&lt;/pre&gt;

	&lt;p&gt;Under the covers, the definition of the closure is the ugly &lt;code&gt;{=&amp;gt;void}&lt;/code&gt; block.  That&amp;#8217;s telling the compiler to create an anonymous interface that has a method named &lt;code&gt;invoke&lt;/code&gt; with no parameters and returns a void.  Ok, time to take a breath.  If we want to add parameters to the invoke method, we have to add them as a comma separated list in front of the &lt;code&gt;=&amp;gt;&lt;/code&gt; symbol.  The &lt;code&gt;void&lt;/code&gt; after the symbol is the return type.  The implementation of this anonymous interface is assigned to the variable name &lt;code&gt;block&lt;/code&gt;.  There&amp;#8217;s a bit more to it, and you can reference variables declared outside the block&amp;#8212;but for the purposes of our conversation let&amp;#8217;s keep it simple.&lt;/p&gt;


	&lt;p&gt;When we pass in our implementation, we use the same basic construct except we add variable names to the parameters and the implementation after the ugly symbol.  We cheated in our example by not having any parameters.  You might think that because the method tells what types the variables are you could skip the type declaration.  You&amp;#8217;d be dead wrong.  Consider the example the spec provides (granted this is from the original specs:&lt;/p&gt;


&lt;pre&gt;
// Define it
{int,int=&amp;gt;int} math;

// Assign it
math = {int x, int y =&amp;gt;
    return x + y;
};

// Invoke it
assert 2 == math.invoke(1, 1);
&lt;/pre&gt;

	&lt;p&gt;&lt;strong&gt;Edit:&lt;/strong&gt; &lt;em&gt;I had to revise my initial reactions based on the input from commenters.&lt;/em&gt;
The Java spec has come a long way.  Although it&amp;#8217;s not perfect (and what in life is?), it is a vast improvement over what we once had.  The critical part of Java closures is that they are really closures.  That means that you can reference variables declared outside the closure (you can&amp;#8217;t do that with anonymous inner classes), and they enable more flexible, robust, and readable code.  At least on the calling side of things.  Java will never match the simplicity and elegance of Ruby, but this time it will be much improved.&lt;/p&gt;


	&lt;h4&gt;The Languages Are Different, Play to Their Strengths&lt;/h4&gt;


	&lt;p&gt;What I don&amp;#8217;t want you to do is walk away with the impression that Ruby is great and Java sucks.  I work with both technologies, one because I want to and the other because I&amp;#8217;m paid to.  They both have their strengths, design idioms, and code aesthetic.  The important thing is to play up the strengths of the language you are using.&lt;/p&gt;


	&lt;p&gt;Just because a solution is elegant in one language doesn&amp;#8217;t mean the same approach translates well to another.  Sometimes it&amp;#8217;s just plain impossible.  Other times, the overall approach is fantastic, but the implementation will have to have subtle differences based on the language you are using.  That&amp;#8217;s OK too.  My Java ActionPack is based on most of the design principles of Ruby&amp;#8217;s action-pack (part of Rails), but they are done in a very Java way.  They evolved differently, appealing to what is considered elegant and good code for the respective languages they are written for.&lt;/p&gt;


	&lt;p&gt;&lt;strong&gt;Edit:&lt;/strong&gt; &lt;em&gt;It appears that there are quite a few things I don&amp;#8217;t quite get about the Java closure spec.  Until we have something solid to play with, everything said is academics.  Neal Grafter is the headmaster for the spec, and he should know better than I about what can and can&amp;#8217;t be done with it.&lt;/em&gt;&lt;/p&gt;</description>
      <pubDate>Sun, 22 Jul 2007 00:00:00 +0000</pubDate>
      <guid isPermaLink="false">urn:uuid:87457913-f285-49b4-8535-da033021ecb8</guid>
      <author>Berin Loritsch</author>
      <link>http://bloritsch.d-haven.net/articles/2007/07/22/judicious-use-of-closures</link>
      <category>ruby</category>
      <category>java</category>
      <category>comparison</category>
      <category>api</category>
      <category>design</category>
      <category>actionpack</category>
    </item>
    <item>
      <title>"Judicious Use of Closures" by Ricky Clarkson</title>
      <description>&lt;p&gt;Java&amp;#8217;s original designers were wrong about operator overloading, maybe on purpose - one of the big selling points was that the hard things about C++ weren&amp;#8217;t present in Java - and operator overloading were a big pain point of C++, at least in theory.&lt;/p&gt;

&lt;p&gt;In practice, there are better operator overloading syntaxes than C++&amp;#8217;s, and they don&amp;#8217;t make things harder to read, unless you use them in a hard to read way.  x.add(y) could easily format your hard drive - there&amp;#8217;s no advantage to x.add(y) over x+y.&lt;/p&gt;

&lt;p&gt;I don&amp;#8217;t like using the control invocation syntax in a non-void context.  I&amp;#8217;d rather use the other syntax to implement a closure that acts as a Comparator.&lt;/p&gt;

&lt;p&gt;My own vote, not that I have one, is for &amp;#8216;return&amp;#8217; to return from the enclosing method in the control invocation syntax, and to return from the closure in the normal syntax.  In other words:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;int x()
{
    blah()
    {
        return 5;  //returns from x()
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;whereas:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;void x()
{
    plus={int x,int y =&amp;gt; return x+y}; //plus.invoke(2,3) returns 5.
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;In the latter case, I&amp;#8217;d have return x+y (without a semicolon) mean the same as return x+y;, and the same as x+y.  Another possibility is just to ban returns from within that kind of closure.&lt;/p&gt;

&lt;p&gt;Neal justifies the approach by saying that the current Java way is broken, and that we shouldn&amp;#8217;t add new broken syntax, and I agree, but I just can&amp;#8217;t justify having x+y and return x+y have different meanings based on that.  For Neal&amp;#8217;s reasoning, see: &lt;a href="http://gafter.blogspot.com/2006/08/tennents-correspondence-principle-and.html" rel="nofollow"&gt;http://gafter.blogspot.com/2006/08/tennents-correspondence-principle-and.html&lt;/a&gt;&lt;/p&gt;</description>
      <pubDate>Mon, 23 Jul 2007 07:05:09 +0000</pubDate>
      <guid isPermaLink="false">urn:uuid:849503ad-62fe-4034-8154-d02deb745a46</guid>
      <link>http://bloritsch.d-haven.net/articles/2007/07/22/judicious-use-of-closures#comment-10</link>
    </item>
    <item>
      <title>"Judicious Use of Closures" by Berin Loritsch</title>
      <description>&lt;p&gt;Neal, It appears there is much I don&amp;#8217;t understand about the way Java plans on doing closures.  I think the biggest issue is going to be the education of users.  I&amp;#8217;d like to think I&amp;#8217;m a pretty smart guy, and if I&amp;#8217;m having this kind of trouble understanding what syntax is being used where, that&amp;#8217;s a problem.  Without a compiler to turn this theory into practice, it&amp;#8217;s really all academic anyway.&lt;/p&gt;</description>
      <pubDate>Mon, 23 Jul 2007 01:57:05 +0000</pubDate>
      <guid isPermaLink="false">urn:uuid:99990d93-6b85-4d4a-b4d2-c79f4687bc22</guid>
      <link>http://bloritsch.d-haven.net/articles/2007/07/22/judicious-use-of-closures#comment-9</link>
    </item>
    <item>
      <title>"Judicious Use of Closures" by Berin Loritsch</title>
      <description>&lt;p&gt;If the {int x, int y =&gt; x+y} format is the case, that gets us closer to Ruby.  I can see where the source of contention would come from.  In Ruby and Smalltalk (and I think Lisp/Scheme) the last statement in a block is the return value&amp;#8211;but in Java we have been told to be explicit with everything every where.  There is a cultural and cognitive clash going on there.  In a sense, for consistency within Java it might be better to have the @return@ syntax.&lt;/p&gt;

&lt;p&gt;As to your latter example, I think it might change too much at once within Java to allow that.  The idiom in Java is to use Comparators and let objects that implement Comparable have a natural order.  The creators of Java believed wholeheartedly that you shouldn&amp;#8217;t allow operator overloading, which also means that operators are not methods, and only exist for primitive types.  You just couldn&amp;#8217;t pass in those methods because they wouldn&amp;#8217;t exist.&lt;/p&gt;

&lt;p&gt;I think the closest you would be able to come with Java would be something like this:&lt;/p&gt;

&lt;p&gt;Collections.sort(MyObject a, MyObject b: list) {
    /* return */ a.getId().compareTo(b.getId())
}&lt;/p&gt;

&lt;p&gt;I&amp;#8217;ll leave the return as it is for now, until the shakedown is done.&lt;/p&gt;</description>
      <pubDate>Mon, 23 Jul 2007 01:47:57 +0000</pubDate>
      <guid isPermaLink="false">urn:uuid:0a43f77d-4699-4d94-8e9d-c16ec1364c8c</guid>
      <link>http://bloritsch.d-haven.net/articles/2007/07/22/judicious-use-of-closures#comment-8</link>
    </item>
    <item>
      <title>"Judicious Use of Closures" by Neal Gafter</title>
      <description>&lt;p&gt;You wrote &amp;#8220;A change in the current spec allows you to rewrite the above a bit differently:&amp;#8221;&amp;#8230; but that is all wrong. The control invocation syntax is for invoking a method that receives a closure, not for writing an assignment to a variable or for writing a closure expression.&lt;/p&gt;

&lt;p&gt;As Ricky pointed out, the &amp;#8220;return&amp;#8221; statement is not how one yields a result from a closure. Rather, the return statement returns from the enclosing method, as it does in Ruby.&lt;/p&gt;</description>
      <pubDate>Mon, 23 Jul 2007 01:36:02 +0000</pubDate>
      <guid isPermaLink="false">urn:uuid:2c9a1919-2529-4c61-acdc-b5781b7b9d53</guid>
      <link>http://bloritsch.d-haven.net/articles/2007/07/22/judicious-use-of-closures#comment-7</link>
    </item>
    <item>
      <title>"Judicious Use of Closures" by Ricky Clarkson</title>
      <description>&lt;p&gt;I think there&amp;#8217;s another mistake - {int x,int y =&gt; return x+y; } - return will return from the surrounding context, not from the closure (yes, this is a point of contention).  {int x,int y =&gt; x+y} is more like it.&lt;/p&gt;

&lt;p&gt;If Java also gained a method reference syntax, say, #&amp;#8217;methodName(int) (rather like Common Lisp), we could potentially apply the same syntax to replace the whole of {int x,int y =&gt; x+y} with #&amp;#8217;+, or {+}, or whatever the syntax actually was.  I think that&amp;#8217;d be good.  Example:&lt;/p&gt;

&lt;p&gt;Collections.sort(list,&amp;#8217;#&amp;lt;); (sorts a list using &amp;lt; as the comparator)&lt;/p&gt;

&lt;p&gt;Essentially, what I like in languages is uniformity - where you don&amp;#8217;t have to do things like surround an operator in an anonymous class to pass it as an operand.  Scheme seems to be the best at that out of the languages I&amp;#8217;ve seen (it doesn&amp;#8217;t even need the #&amp;#8217; syntax).  The above sorting example would be:&lt;/p&gt;

&lt;p&gt;(sort list &amp;lt;)&lt;/p&gt;</description>
      <pubDate>Sun, 22 Jul 2007 22:08:24 +0000</pubDate>
      <guid isPermaLink="false">urn:uuid:3e307a3b-8a80-45a2-b23d-d818884fc4c0</guid>
      <link>http://bloritsch.d-haven.net/articles/2007/07/22/judicious-use-of-closures#comment-6</link>
    </item>
    <item>
      <title>"Judicious Use of Closures" by Berin Loritsch</title>
      <description>&lt;p&gt;I&amp;#8217;ve edited the Java portion of the entry, as the alternative syntax really does make a difference.  Thanks for your comments, it helped me to understand the spec a little better.&lt;/p&gt;</description>
      <pubDate>Sun, 22 Jul 2007 19:29:28 +0000</pubDate>
      <guid isPermaLink="false">urn:uuid:a6422d33-544e-4481-bc37-c7161a6a40d6</guid>
      <link>http://bloritsch.d-haven.net/articles/2007/07/22/judicious-use-of-closures#comment-5</link>
    </item>
    <item>
      <title>"Judicious Use of Closures" by Berin Loritsch</title>
      <description>&lt;p&gt;I couldn&amp;#8217;t figure out from the spec (which suffers from specifese) that there was the alternate invocation syntax.  The alternate syntax specification makes this a palatable solution in Java.  I&amp;#8217;ll keep that in mind when I provide a finite state machine example where closures would be prefect.&lt;/p&gt;

&lt;p&gt;I&amp;#8217;m really happy that Java Closures is moving in this direction.  It makes it feel like a first class citizen, and almost has me salivating for whenever they come.  Hopefully it is soon.&lt;/p&gt;</description>
      <pubDate>Sun, 22 Jul 2007 18:53:03 +0000</pubDate>
      <guid isPermaLink="false">urn:uuid:cbc1df76-cbdd-4a69-8370-bdad5a743871</guid>
      <link>http://bloritsch.d-haven.net/articles/2007/07/22/judicious-use-of-closures#comment-4</link>
    </item>
    <item>
      <title>"Judicious Use of Closures" by Neal Gafter</title>
      <description>&lt;p&gt;Besides the point that Ricky made (you chose to use the ugliest syntax possible for the invocation of withRole), you appear to be missing one of the greatest benefits of closures over anonymous inner classes.  See &lt;a href="http://www.parleys.com/display/PARLEYS/Closures%20for%20Java" rel="nofollow"&gt;http://www.parleys.com/display/PARLEYS/Closures%20for%20Java&lt;/a&gt;&lt;/p&gt;</description>
      <pubDate>Sun, 22 Jul 2007 18:10:36 +0000</pubDate>
      <guid isPermaLink="false">urn:uuid:655db455-5726-4bda-aa9a-fb6411739580</guid>
      <link>http://bloritsch.d-haven.net/articles/2007/07/22/judicious-use-of-closures#comment-3</link>
    </item>
    <item>
      <title>"Judicious Use of Closures" by Ricky Clarkson</title>
      <description>&lt;p&gt;You missed a bit of the closures spec, namely the control invocation syntax:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;user.withRole("Admin")
{
    Article.find(id).destroy();
    sendMessage( "Article was successfully deleted." );
}
&lt;/code&gt;&lt;/pre&gt;</description>
      <pubDate>Sun, 22 Jul 2007 13:17:08 +0000</pubDate>
      <guid isPermaLink="false">urn:uuid:d2f6a40a-6c42-47df-881b-754cced6dd5e</guid>
      <link>http://bloritsch.d-haven.net/articles/2007/07/22/judicious-use-of-closures#comment-2</link>
    </item>
  </channel>
</rss>
