<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>The Cafes &#187; Blogroll</title>
	<atom:link href="http://cafe.elharo.com/category/blogroll/feed/" rel="self" type="application/rss+xml" />
	<link>http://cafe.elharo.com</link>
	<description>Longer than a blog; shorter than a book</description>
	<lastBuildDate>Sat, 30 Mar 2013 11:51:03 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.5.1</generator>
		<item>
		<title>Voting for Checked Exceptions</title>
		<link>http://cafe.elharo.com/blogroll/voting-for-checked-exceptions/</link>
		<comments>http://cafe.elharo.com/blogroll/voting-for-checked-exceptions/#comments</comments>
		<pubDate>Wed, 30 May 2007 09:51:03 +0000</pubDate>
		<dc:creator>Elliotte Rusty Harold</dc:creator>
				<category><![CDATA[Blogroll]]></category>

		<guid isPermaLink="false">http://cafe.elharo.com/java/voting-for-checked-exceptions/</guid>
		<description><![CDATA[Yet another hideous idea from the closures camp: removing checked exceptions from the language. Now they want to remove one of the features from Java that actually works to support their pet obfuscation. According to Neal Gafter: We did a Google search to see how many people have written in support of checked exceptions and [...]]]></description>
				<content:encoded><![CDATA[<p><a href="http://gafter.blogspot.com/2007/05/removing-language-features.html">Yet another hideous idea from the closures camp</a>: removing checked exceptions from the language. Now they want to remove one of the features from Java that actually works to support their pet obfuscation. </p>
<p>According to Neal Gafter:</p>
<blockquote><p>We did a Google search to see how many people have written in support of checked exceptions and how many people don&#8217;t like them. The discussion seems to be lopsided against checked exceptions, but on the other hand that may be due to the fact that checked exceptions are the status quo.</p></blockquote>
<p>For his next Google search, let me just say, I like checked exceptions and I want to keep them. The people who object to checked exceptions mostly seem not to know the difference between checked and unchecked. Most importantly, they seem not to know when to use checked exceptions and when to use unchecked exceptions. A few libraries such as the Java USB API even get this exactly backwards. And I will admit, if you don&#8217;t know this crucial piece of information, then checked exceptions seem ugly and confusing.<br />
<span id="more-222"></span></p>
<p>However, if you do understand the difference Java&#8217;s exception handling is the single best error handling and reporting mechanism ever built into a programming language. It is a strength of the language, not a weakness. To date, I don&#8217;t think any other language has come close to matching Java&#8217;s robust exception handling, and resistance to distinguishing checked from unchecked exceptions is the reason why. </p>
<p>I don&#8217;t have time this morning to explain the exact difference between checked and unchecked exceptions, so just go read section 8 of <a href="http://www.amazon.com/exec/obidos/ISBN=0201310058/ref=nosim/cafeaulaitA">Effective Java</a>, particularly items 40 and 41. In brief, checked exceptions are for unpredictable environmental conditions such as I/O errors and XML well-formedness violations while unchecked exceptions are for program failures that should be caught during testing, such as array index out of bounds or null pointers. A checked exception usually cannot be avoided by changing your code while an unchecked exception usually can be.  That is, an unchecked exception normally indicates a bug in your program, and a checked exception doesn&#8217;t. That&#8217;s why we have to catch or declare checked exceptions and not runtime exceptions. A runtime exception will usually occur every time the code takes a particular path, whereas a checked exception may occur some times when a program runs through a path and not others, because checked exceptions depend on environmental conditions outside the program&#8217;s direct control. Therefore a problem that causes a runtime exception should be detected and fixed during testing, whereas a checked exception may well only appear in a customer environment. Anybody who doesn&#8217;t understand this has no business pontificating about exception handling in Java.</p>
<p>But please: can we take the idea of removing checked exceptions from the language off the table? They are far more important to developing reliable, comprehensible, robust code than closures ever could be. Closures are just syntax sugar that don&#8217;t let you do anything you can&#8217;t do in other ways already. Checked exceptions are a much more core feature that cannot be replaced with a little syntax sugar. </p>
]]></content:encoded>
			<wfw:commentRss>http://cafe.elharo.com/blogroll/voting-for-checked-exceptions/feed/</wfw:commentRss>
		<slash:comments>152</slash:comments>
		</item>
		<item>
		<title>Menu Icons Considered Ugly</title>
		<link>http://cafe.elharo.com/blogroll/menu-icons-considered-ugly/</link>
		<comments>http://cafe.elharo.com/blogroll/menu-icons-considered-ugly/#comments</comments>
		<pubDate>Mon, 28 May 2007 09:30:46 +0000</pubDate>
		<dc:creator>Elliotte Rusty Harold</dc:creator>
				<category><![CDATA[Blogroll]]></category>
		<category><![CDATA[Macs]]></category>
		<category><![CDATA[User Interface]]></category>

		<guid isPermaLink="false">http://cafe.elharo.com/java/menu-icons-considered-ugly/</guid>
		<description><![CDATA[There&#8217;s a common but mistaken belief that proper user interface design requires lots of pictures and icons. In fact, it doesn&#8217;t. Many concepts and actions can be fully and best conveyed by text. While standard icons for directories and disks and the like can be helpful, custom icons for an application&#8217;s unique actions rarely are. [...]]]></description>
				<content:encoded><![CDATA[<p>There&#8217;s  a common but mistaken belief that proper user interface design requires lots of pictures and icons. In fact, it doesn&#8217;t. Many concepts and actions can be fully and best conveyed by text. While standard icons for directories and disks and the like can be helpful, custom icons for an application&#8217;s unique actions rarely are. The fact is, most icons are not self-explanatory; and if they&#8217;re not common enough to be standardized, they&#8217;re not common enough to be learned easily.  </p>
<p>Nonetheless, many applications persist in creating pointless, incomprehensible toolbars. Icon design is hard. It is not something that just any art school graduate with mad Photoshop skills can accomplish. Icon design is about conveying an idea with pictures. not merely making a 32&#215;32 bitmap look pretty. It&#8217;s hard enough coming up with a good icon for basic actions like cut and paste. Now try imagining one for &#8220;Analyze Module Dependencies&#8221; or &#8220;View Breakpoints&#8221;. There&#8217;s a reason <a href="http://en.wikipedia.org/wiki/Susan_Kare">Susan Kare</a> gets the big bucks.</p>
<p>Lately, this trend seems to have seeped into menus, where text used to rule supreme. For instance, look at this File menu from IntelliJ IDEA 6.0:</p>
<p><img src='http://cafe.elharo.com/wp-content/uploads/2007/05/menuicons.png' alt='menuicons.png' alt="New Project... New Module... Open Project... Icon Open File... Reopen Close Project Icon Settings... Template Project Settings... Icon Save All Export Settings... Import Settings..."/></p>
<p>Not only do the icons add nothing to the menu items. They actually make the menu harder to scan and read because the items are no longer left aligned.<br />
<span id="more-217"></span></p>
<p>By contrast consider this File menu from Firefox:</p>
<p><img src='http://cafe.elharo.com/wp-content/uploads/2007/05/menunoicons.png' alt='New Window New Tab Open Locationâ€¦ Open Fileâ€¦ Close' /></p>
<p>Notice how much cleaner and easier to read it is? The eye can scan straight down the left hand side looking for the item it wants. There&#8217;s a reason books, newspapers, and websites all use left aligned columns.<sup><a href="#f1">1</a></sup></p>
<p>Swing is partially to blame here. The <code><a href="http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/Action.html">Action</a></code> interface encourages programmers to add icons to every action, and then displays those icons in the menus and the toolbars.  However icons only belong in toolbars, not menus. Swing should be configured to never show icons in menus. I suspect Swing is merely trying to support a bad user interface design from Windows and Linux. I could be wrong, but off the top of my head I don&#8217;t think I&#8217;ve ever seen a native Mac app make this particular mistake.<sup><a href="#f2">2</a></sup> However, on Windows and Linux/Gnome it&#8217;s endemic.<sup><a href="#f2">3</a></sup </p>
<p>If you simply cannot resist the urge to add icons to your menus, at least do this: add icons to every item, even blank icons if you must, to make sure all the menu items are properly left aligned. Gnome gets at least this much right, as shown in this File menu from the Gimp:</p>
<p><img src='http://cafe.elharo.com/wp-content/uploads/2007/05/gnomemenu1.png' alt='Icon Newâ€¦ Icon Openâ€¦' /></p>
<p>Windows gets this right too, and properly aligns the text even when some menu items have icons and some don&#8217;t. Java apps are really the odd ones out here. </p>
<p>But really, icons don&#8217;t belong in menus and never have. Menus are for text. Toolbars are for icons, and you shouldn&#8217;t mix the two.</p>
<hr />
<span class="footnote" id='f1'><sup>1</sup> Assuming a left to right language such as English or French, of course. </span></p>
<p><span class="footnote" id='f2'><sup>2</sup> The Finder actually does display icons in some of its optional menus: Script, Input, and Accounts. The Input menu at least has the excuse that a potential user may not be able to read the text but can pick a flag. However the Script menu has no excuse. In all three cases, the Finder misaligns the menu items. </span></p>
<p><span class="footnote" id='f3'><sup>3</sup> I don&#8217;t use KDE, so I don&#8217;t know if it shows up there too. Anyone happen to know?</span></p>
]]></content:encoded>
			<wfw:commentRss>http://cafe.elharo.com/blogroll/menu-icons-considered-ugly/feed/</wfw:commentRss>
		<slash:comments>35</slash:comments>
		</item>
		<item>
		<title>Type Inference: Another Bad Idea for Java 7</title>
		<link>http://cafe.elharo.com/blogroll/type-inference-another-bad-idea-for-java-7/</link>
		<comments>http://cafe.elharo.com/blogroll/type-inference-another-bad-idea-for-java-7/#comments</comments>
		<pubDate>Mon, 16 Apr 2007 12:13:55 +0000</pubDate>
		<dc:creator>Elliotte Rusty Harold</dc:creator>
				<category><![CDATA[Blogroll]]></category>

		<guid isPermaLink="false">http://cafe.elharo.com/java/type-inference-another-bad-idea-for-java-7/</guid>
		<description><![CDATA[Peter von der Ahé and a few others are pushing type inference in Java 7. The goal is to not have to explicitly declare local variable types. Remi Forax offers this example: // print a frequency table of words public static void main(String[] args) { map := new HashMap&#60;String, Integer&#62;(); for(word : args) { freq [...]]]></description>
				<content:encoded><![CDATA[<p><a href="http://java.sun.com/developer/Meet-Eng/vonderahe/">Peter von der Ahé</a> and a few others are pushing type inference in Java 7. The goal is to not have to explicitly declare local variable types. Remi Forax offers <a href="http://weblogs.java.net/blog/forax/archive/2006/12/call_me_santa.html">this example</a>:</p>
<pre>  // print a frequency table of words
  public static void main(String[] args) {
    map := new HashMap&lt;String, Integer&gt;();
    for(word : args) {
      freq := map.get(word);
      map.put(word, (freq==null) ? 1 : freq+1);
    }
    System.out.println(map);
  }</pre>
<p><span id="more-207"></span></p>
<p>Peter von der Ahe and Christian Plesner Hansen suggest reusing the <code>final</code> keyword instead:</p>
<pre>  public static void main(String[] args) {
    final map = new HashMap&lt;String, Integer&gt;();
    for(final word : args) {
      final freq=map.get(word);
      map.put(word, (freq==null) ? 1 : freq+1);
    }
    System.out.println(map);
  }</pre>
<p>Note that both proposals have the side effect of making the local variable final, as well as inferring its type, although it&#8217;s more explicit in the AhÃ© proposal.</p>
<p>Type inference actually makes some sense in languages like JavaScript and PHP that are built around this, and had this feature from day 1. It makes no sense in a language like Java that&#8217;s built around the opposite. It makes Java look weakly typed, but it isn&#8217;t. In fact, if anything this is now more strongly typed because, for example, you have to type a <code>Map</code> variable as a <code>HashMap</code> or a <code>TreeMap</code> rather than just a Map. That is,</p>
<p><code>map := new HashMap();</code></p>
<p>is equivalent to </p>
<p><code>HashMap map = new HashMap();</code></p>
<p>not</p>
<p><code>Map m = new HashMap(); </code></p>
<p>Much more importantly, though, it&#8217;s more syntax that makes the language larger and harder to learn. I used to be able to teach pretty much all the important parts of Java in one semester. Now I can&#8217;t even think about doing generics, annotations, and enums unless I drop GUIs. Java 1.0 was designed as a good teaching language. Java 1.1 was pretty good too. Every piece added to it since then&mdash;anonymous inner classes, <code>strictfp</code>, closures, enhanced for loop, generics, type inference, etc.&mdash;made it less suitable for that purpose.  </p>
<p>Even if I try to teach type inference, I have to cover a lot of special cases, and explain what it means to make a local variable final first, and why you might want to do that. This makes some sense to those of us who&#8217;ve been breathing this stuff for 10+ years now. It makes no sense at all to anyone who&#8217;s coming to the language for the first time. It&#8217;s just one more source of weird, incomprehensible compiler error messages they have to ask their professor to debug for them. Is this really worth saving a few keystrokes of typing?</p>
<p>It&#8217;s time to call a halt to new features in the Java language. I am not saying that the features are wrong, just that they don&#8217;t fit into the language any more. It&#8217;s already too bloated. I am not saying that generics, type inference, closures, compiler created factory methods, and other kitchen sink proposals are bad. They&#8217;re not. I am saying that they simply don&#8217;t fit into or with the current core language, and every one we add makes the language worse, not better.</p>
<p>If these features are necessary, and some of them may be, then they should be designed into a <em>new</em> language from the beginning. This new language could have real generics without type erasure. It could have <code>:=</code> but not <code>=</code>. It could have factory methods and not have constructors. It could have closures and not have anonymous inner classes. That would be a language that made sense, and that you could still teach in one semester without tripping over 37 different special cases.</p>
<p>However the current push to add new language features to Java without taking anything away must stop. Every single one makes the language worse, not better. Every single one makes Ruby and C# and Python look more attractive. You cannot build on top of an old foundation forever. Fifty story skyscrapers cannot be built by adding floors to a five-story tenement. Sometimes you have to move down the block and start building in a new lot. For Java, that time has come. </p>
]]></content:encoded>
			<wfw:commentRss>http://cafe.elharo.com/blogroll/type-inference-another-bad-idea-for-java-7/feed/</wfw:commentRss>
		<slash:comments>61</slash:comments>
		</item>
		<item>
		<title>Unrolling Code Closures for Undergraduates</title>
		<link>http://cafe.elharo.com/blogroll/unrolling-code-closures-for-undergraduates/</link>
		<comments>http://cafe.elharo.com/blogroll/unrolling-code-closures-for-undergraduates/#comments</comments>
		<pubDate>Fri, 30 Mar 2007 02:02:08 +0000</pubDate>
		<dc:creator>Elliotte Rusty Harold</dc:creator>
				<category><![CDATA[Blogroll]]></category>

		<guid isPermaLink="false">http://cafe.elharo.com/java/unrolling-code-closures-for-undergraduates/</guid>
		<description><![CDATA[One consistent tendency I&#8217;ve noticed among undergraduate programmers is a persistent and incorrect belief that the number of lines of code is somehow tied to code efficiency. The thinking goes that the fewer lines they have, the faster the program will run. (Why they even care about speed at all is a story for another [...]]]></description>
				<content:encoded><![CDATA[<p>One consistent tendency I&#8217;ve noticed among undergraduate programmers is a persistent and incorrect belief that the number of lines of code is somehow tied to code efficiency. The thinking goes that the fewer lines they have, the faster the program will run. (Why they even care about speed at all is a story for another day.) For example, they get peeved when I write this:</p>
<pre><code>int x;
int y;
int z;</code></pre>
<p>instead of this:</p>
<p><code>int x, y, z;</code></p>
<p>The brighter ones may not be bothered by that, but this gets them all in a tizzy, nonetheless:</p>
<pre><code>int low  = 1;
int high = 1;
for (int i = 0; i &lt; 50; i++) {
  System.out.print(low);
  int temp = high;
  high = high + low;
  low = temp;
}</code></pre>
<p>They want to see this</p>
<pre><code>int low  = 1;
int high = 1;
int temp;
for (int i = 0; i &lt; 50; i++) {
  System.out.print(low);
  temp = high;
  high = high + low;
  low = temp;
}</code></pre>
<p>They love taking code out of a loop, even when the code in question (a declaration) doesn&#8217;t actually do anything; and they certainly don&#8217;t care if their resulting code is less readable. In fact, they sort of take it as a mark of honor if their code looks complex. They&#8217;re going to love closures.<br />
<span id="more-175"></span></p>
<p>I&#8217;m reading proposals like CICE and I see examples like this:</p>
<pre><code>    new Thread(new Runnable() {
        public void run() {
            foo();
        }
    }).start();</code></pre>
<p>and this:</p>
<p><code>    new Thread(Runnable(){ foo(); }).start();</code></p>
<p>But both of these are bad examples! Both the closure and the non-closure syntax are more confusing and harder to read than they should be. I have to spend a lot of time puzzling over them and carefully decoding the interactions of the different parentheses and braces and periods and semicolons just to understand what either one is doing. Instead the non-closure syntax should be written like this:</p>
<pre><code>Runnable r = new Runnable() {
        public void run() {
            foo();
        }
    };
Thread t = new Thread(r);
t.start();</code></pre>
<p>In fact, I might even go so far as to move the runnable into a non-anonymous class so it&#8217;s even clearer what&#8217;s happening. </p>
<p>The more code you stuff into a line or into a single statement the harder the code is to read, and the harder it is to debug. The closure proposals seem to be all about stuffing more code into a line. I want less, not more. I want a syntax that more closely reflects what the compiler and interpreter are actually doing. That&#8217;s why I like using a separate line for each variable declaration, and it&#8217;s why I like named classes instead of anonymous classes.</p>
<p>One thing I don&#8217;t like about both of the extant proposals for closures (CICE and Gafter, et al)  is that they hide what they&#8217;re doing. They pretend they&#8217;re giving us first class functions but what they&#8217;re really giving us are even more anonymous inner classes. This is the type erasure mistake all over again. The syntax is hiding what the compiler is really doing.</p>
<p>We may indeed need closures, but if we do they should be real first class functions, not fakes implemented with still more compiler wizardry. If this requires changes at the VM level, so be it. If the feature isn&#8217;t worth changing the VM over, then don&#8217;t implement it. It probably isn&#8217;t all that important anyway. But let&#8217;s do away with syntax that hides what&#8217;s really happening.</p>
]]></content:encoded>
			<wfw:commentRss>http://cafe.elharo.com/blogroll/unrolling-code-closures-for-undergraduates/feed/</wfw:commentRss>
		<slash:comments>17</slash:comments>
		</item>
		<item>
		<title>What Java Still Can&#8217;t Do</title>
		<link>http://cafe.elharo.com/blogroll/what-java-still-cant-do/</link>
		<comments>http://cafe.elharo.com/blogroll/what-java-still-cant-do/#comments</comments>
		<pubDate>Fri, 23 Mar 2007 21:14:48 +0000</pubDate>
		<dc:creator>Elliotte Rusty Harold</dc:creator>
				<category><![CDATA[Blogroll]]></category>

		<guid isPermaLink="false">http://cafe.elharo.com/java/what-java-still-cant-do/</guid>
		<description><![CDATA[It&#8217;s hard to believe that more than a decade after Java was released, there are still so many tasks it can&#8217;t do. I&#8217;m not just talking about things it can&#8217;t do well, but about things that you just can&#8217;t do without shelling out to native code. Here is a list of tasks that still need [...]]]></description>
				<content:encoded><![CDATA[<p>It&#8217;s hard to believe that more than a decade after Java was released, there are still so many tasks it can&#8217;t do. I&#8217;m not just talking about things it can&#8217;t do well, but about things that you just can&#8217;t do without shelling out to native code. Here is a list of tasks that still need native code:<br />
<span id="more-165"></span></p>
<ul>
<li>Firewire</li>
<li>Raw IP</li>
<li>ICMP</li>
<li>Raw Ethernet</li>
<li>In fact, any networking besides TCP or UDP</li>
<li>Burn a CD/DVD</li>
<li>Rip a CD/DVD</li>
<li>Raw console access; e.g. curses, clear screen, etc. (To be honest this one is so old-fashioned, it shouldn&#8217;t be added.)</li>
<li>Copy or move a file (with all metadata intact)</li>
</ul>
<p>Isn&#8217;t it about time we filled some of these holes? Why has it taken 12 years to add something as basic as copying a file?</p>
<p>What else can you think of?</p>
]]></content:encoded>
			<wfw:commentRss>http://cafe.elharo.com/blogroll/what-java-still-cant-do/feed/</wfw:commentRss>
		<slash:comments>52</slash:comments>
		</item>
		<item>
		<title>Homework for Closures</title>
		<link>http://cafe.elharo.com/blogroll/homework-for-closures/</link>
		<comments>http://cafe.elharo.com/blogroll/homework-for-closures/#comments</comments>
		<pubDate>Thu, 01 Mar 2007 13:58:18 +0000</pubDate>
		<dc:creator>Elliotte Rusty Harold</dc:creator>
				<category><![CDATA[Blogroll]]></category>

		<guid isPermaLink="false">http://cafe.elharo.com/java/homework-for-closures/</guid>
		<description><![CDATA[I&#8217;ve long been an advocate of outside-in API design. This reflects my interest in user-interface principles in API design. When designing a GUI it is customary to mock it up on paper and then with prototyping tools before implementing the internal code. This helps the interface reflect the user&#8217;s goals and expectations rather than the [...]]]></description>
				<content:encoded><![CDATA[<p>I&#8217;ve long been an advocate of outside-in API design. This reflects my interest in user-interface principles in API design. When designing a GUI it is customary to mock it up on paper and then with prototyping tools before implementing the internal code. This helps the interface reflect the user&#8217;s goals and expectations rather than the internal data structures of the program. In API design, this means the class becomes more easily usable by decoupled client code.</p>
<p>It occurs to me that the same principles apply in language design. In particular we should try writing some code with proposed new features <em>before</em> we implement the features. This has several advantages:</p>
<ul>
<li>Ensures we get what we need, rather than what the proposal supports</li>
<li>Helps us understand exactly what is being proposed</li>
<li>Shows the strengths and weaknesses of each proposal</li>
<li>Avoids unnecessary features that don&#8217;t support a real use case </li>
</ul>
<p>Consequently herewith are some challenges for the proposers of the various closure proposals. I&#8217;ve tried to make them as simple as possible so that the closure issues will be focused on.<br />
<span id="more-191"></span></p>
<h2>Single Method EventListener</h2>
<p>Write a Swing applet containing a single button which pops up a <code>JOptionPane</code> containing the message &#8220;Hello closures&#8221; when pressed.</p>
<h3>Solutions</h3>
<ul>
<li><a href="http://www.cafeaulait.org/src/HelloClosuresApplet.java">Java 1.4</a></li>
</ul>
<h2>Single Method EventListener, Part 2</h2>
<p>I&#8217;m still playing with this idea, but I suspect we should try passing in some data from both fields and local variables to be displayed in the <code>JOptionPane</code>. Let&#8217;s try passing in a value from a param tag. </p>
<h3>Solutions</h3>
<ul>
<li><a href="http://www.cafeaulait.org/src/HelloParam.java">Java 1.4</a></li>
</ul>
<h2>MultiMethod EventListener</h2>
<p>Write an applet such as <a href="http://www.cafeaulait.org/books/jdr/examples/13/EventTutor.java">this very old one</a> that reports all mouse and key events, except for mouse moved events. Thus you&#8217;re likely using two event listener interfaces: <code>KeyListener</code> and <code>MouseListener</code>.</p>
<p>(This is a weak problem. There may be a better one, if anyone cares to suggest. The idea though is to set up a well known interface that has more than one method which must be implemented.)</p>
<h2>Multithreaded? Server</h2>
<p>Write a network server which receives a single String on a line as input. Parse this string as an int. Assuming this is a non-negative integer, return the n<i>th</i> Fibonacci number as a string. Then close the connection.</p>
<p>Do not assume either the  output is within the range of an <code>int</code>, <code>long</code>, or <code>double</code>. (I.e. you have to use <code>BigInteger</code>.) </p>
<p>Because Fibonacci numbers grow like O(n^2) and because you have to use <code>BigInteger</code>, you cannot serialize the requests. That is, you cannot process them in sequence and wait for one to be calculated before serving the next. I suspect you need multiple threads to make this work, but it&#8217;s just possible someone clever enough could avoid that.</p>
<p>On the other hand, I&#8217;d prefer you not to store a humongous lookup table in a file or database somewhere. Yes, that would be sensible; but the specific goal here is to test cases where the server has to do a lot of work for each connection and still process a lot of simultaneous connections.</p>
<h3>Solutions</h3>
<ul>
<li><a href="http://www.cafeaulait.org/src/FibServer.java">Java 1.4</a></li>
</ul>
<h2>Multithreaded Program</h2>
<p>Write a program that makes efficient use of potentially dozens or hundreds of CPUs to multiply two large matrixes containing doubles. Essentially we&#8217;re looking for a reasonable implementation of this method:</p>
<p><code>public static double[][] multiply (double[][] a, double[][] b)</code></p>
<p>Throw an <code>IllegalArgumentException</code> if the dimensions don&#8217;t match up, but the interesting case is when they do. </p>
<p>You can parameterize the number of CPUs if you like. </p>
<p>You can remove the <code>static</code> keyword if you must, but I&#8217;d be much more impressed if you don&#8217;t have to do that.</p>
<h3>Solutions</h3>
<ul>
<li><a href="http://www.cafeaulait.org/src/MatrixMultiply.java">Java 1.4</a> (Needs some work)</li>
</ul>
<h2>Sorting #1</h2>
<p>Write a program which sorts two arbitrary lists, using a user-supplied comparison function. You do not have to use the Java Collections API, though you may if you like.</p>
<h3>Solutions</h3>
<p>It turns out the Collections API handles almost all of this:</p>
<ul>
<li><a href="http://www.cafeaulait.org/src/SorterTest.java">Java 1.4</a> (Demo&#8217;d as a JUnit test case)</li>
</ul>
<h2>Sorting #2</h2>
<p>Write a program which sorts a <code>double[]</code> array using a user supplied sort function.</p>
<h2>Iteration</h2>
<p>Write a class which calculates the average of a <code>java.util.List</code> using a user-supplied average function.</p>
<p>Demonstrate the use of this class with three different average functions&#8211;mean, median, and mode&#8211;on three different types: <code>java.lang.Double</code>, <code>java.lang.String</code>, and autoboxed ints.</p>
<h2>Error Handling</h2>
<p>Write a program to write the first 25 Fibonacci numbers into the file named &#8220;fibonacci.txt&#8221; in the current working directory, which may or may not already exist, may or may not be writable, and must be closed on program completion. (I don&#8217;t care whether you write text or binary numbers.)</p>
<h3>Solutions</h3>
<ul>
<li><a href="http://www.cafeaulait.org/src/FibonacciFile.java">Java 1.4</a></li>
</ul>
<h2>Synchronization</h2>
<p>This one&#8217;s from Neal Gafter, and I&#8217;m still trying to make more fully understand it, but I think the problem statement is along the lines, &#8220;Given a <code>CandidatePool extends Collection&lt;Candidate></code>&#8221; which is shared between multiple threads, find a candidate in the pool that meets the requirements, remove it from the pool, and return it. The <code>Candidate</code> interface/class has methods such that the following makes sense</p>
<pre><code>class Main {
    /** Find a candidate that meets the requirements */
    Candidate recruit(CandidatePool candidates,
                      Set<Qualification> requirements) {
            for (Candidate c : candidates) {
                if (c.qualifications().containsAll(requirements)) {
                    candidates.remove(c);
                    return c;
                }
            }
        return recruitForeign(requirements);
    }
    /** Find a candidate meeting the requirements from another pool. */
    static Candidate recruitForeign(Set<Qualification> requirements) {
        return null; // placeholder implementation
    }
}<code></pre>
<p>This version is <em>not</em> thread-safe. Making it thread-safe is part of the problem. </p>
<p>According to Gafter, you must also "properly use the Lock API instead of the language's synchronized statement." That requirement sounds suspicious to me, but he knows much more about threads than I do, so presumably there's some reason to prefer the Lock API to mere synchronization.</p>
<h2>Fairness</h2>
<p>Now take this same problem, and make it not just thread-safe but fair among threads.    That may be where the Lock API comes in. I'm still trying to grok this problem. </p>
<h2>Have I missed anything?</h2>
<p>I'm not sure any of these problems require access to local variables, non-final local variables, or instance fields and methods from the enclosing class. Since those are major sticking points for the various proposals that help distinguish between them, that may be a problem. Then again maybe I shouldn't be focused on that at all, only on the real use case. If we don't have any use cases that need that, maybe that just isn't so important.</p>
<p>Personally I'm beginning to wonder if we need anything more than mere function pointers. Why not just allow <code>a.doSomething</code>, <code>this.doSomething</code>, and <code>Class.doSomething</code> to be passed to methods, and define a syntax for invoking these things within the methods they're passed to? This is close to the Colebourne proposal, but eliminates anonymous inner methods. I don't see why we need to define functions inline inside other functions. In fact, I think I'd prefer we didn't. This would neatly avoid all the questions about this, and local variables in scope being final or not. Hmm, I may have to write some sample code myself, to see if this idea holds water. <img src='http://cafe.elharo.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<h2>Submitted Solutions</h2>
<ul>
<li>BGGA: Pending</li>
<li>CICE: Pending</li>
<li>First-class methods: Pending</li>
<li>Harold (Function pointers only, no inline methods): Pending</li>
<li>Java 1.4: Pending</li>
<li>Java 5: Pending</li>
<li>Java 6: Pending</li>
</ul>
<p>Once the problems are fleshed out a bit more, and I've incorporated feedback, I'll probably do a table mapping solutions to proposals. </p>
<h2>Thoughts</h2>
<p>I think these are all pretty basic problems that shouldn't take too long for any of the minds working on closure proposals. However, seeing and comparing the solutions should give the rest of us a much better way of judging and evaluating  the relative merits of the different proposals. </p>
<p>I request that each proposer publish a page showing the detailed code to implement each of the following problems.  Furthermore if anyone wants to solve these just using Java 1.4, 5, or 6 feel free. I'll link to solution sets as they become available. And please do suggest other use cases since I'm sure I haven't hit all of them. If any of the problems are insufficiently clear, let me know and I'll try to elaborate. And if you disagree with any of the use cases, comment about that too. </p>
<p>Gentlemen, start your editors. </p>
<h2>Caveat</h2>
<p>I am a little worried that these problems are too small and too focused on exactly what closures do. While this may help us compare proposals, it doesn't really help us decide if any proposal is worth the cost compared to doing nothing. This is like optimization: you don't want to spend a huge effort speeding up part of your program where it only spends a tenth of a percent of its time. We don't want a huge increase in language complexity to organize a piece of the language most programmers never see. </p>
<p>While all the use cases mentioned here certainly arise in Java code, I don't know that they're truly the pain points Java programmers face, or the most frequent ones. Some criteria any new language feature must pass should include:</p>
<ul>
<li>Does it let us do anything we can't do now?</li>
<li>Does it make the code we are writing now easier to write?</li>
<li>Does it make the code we are writing now easier to <em>read</em>?</li>
</ul>
<p>The most I'm willing to answer for closures on each of those so far is maybe. On the third, I'm tempted to answer no.</p>
]]></content:encoded>
			<wfw:commentRss>http://cafe.elharo.com/blogroll/homework-for-closures/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>Two Criteria for Closures</title>
		<link>http://cafe.elharo.com/blogroll/two-criteria-for-closures/</link>
		<comments>http://cafe.elharo.com/blogroll/two-criteria-for-closures/#comments</comments>
		<pubDate>Thu, 15 Feb 2007 15:31:11 +0000</pubDate>
		<dc:creator>Elliotte Rusty Harold</dc:creator>
				<category><![CDATA[Blogroll]]></category>

		<guid isPermaLink="false">http://cafe.elharo.com/java/two-criteria-for-closures/</guid>
		<description><![CDATA[I&#8217;m slowly coming around to the idea that first class functions in Java are probably a good idea. I&#8217;m still not convinced we need full-blown closures though. Possibly we do. Doug Lea has some interesting use cases I need to explore further. Several things concern me though. One is syntax. I really, really want the [...]]]></description>
				<content:encoded><![CDATA[<p>I&#8217;m slowly coming around to the idea that first class functions in Java are probably a good idea. I&#8217;m still not convinced we need full-blown closures though. Possibly we do. Doug Lea has some interesting use cases I need to explore further.</p>
<p>Several things concern me though. One is syntax. I really, really want the syntax to be simple and have no surprises or significant learning curve. I want existing Java programmers to be able to read Java code that uses closures (or first class functions) and immediately be able to see what the code is doing without any prior training in the new syntax. I want the syntax to be that clear. If we can&#8217;t have that, I don&#8217;t want to do it. I want Java to still be a <a href="http://cafe.elharo.com/java/java-as-lingua-franca/">lingua franca</a>.</p>
<p>Secondly I want closures to be really, really easy to write. No gotchas. A little training may be allowed here, but there shouldn&#8217;t be any special cases or surprises. Programmers&#8217; first instincts of how to write something should be correct. In particular, I do not want to see any issues like &#8220;the closure works if the external variables are declared final, but fails if they&#8217;re not.&#8221; Or, &#8220;the closure works if the external variables are not modified, but stops compiling if a line is added that modifies one.&#8221; That is, implicit final is not a workaround. The only things that break the closure should be:</p>
<ol>
<li> Syntax error inside the closure itself</li>
<li> Breakage in the closure syntax (i.e. leaving off a trailing curly brace or some such in the closure definition)</li>
<li> Removing or renaming an external variable the closure depends on.</li>
</ol>
<p>In other words, the only things that should cause a closure to fail to compile or run in the expected fashion should be exactly those things that cause today&#8217;s code to fail to compile or run. If you rename a local variable from <code>x</code> to <code>y</code> and forget to rewrite the statement <code>foo(x);</code>, then  the compiler complains. This is a common bug we all know how to handle when it happens to us.  I want to make sure that adding closures does not add any new failure types or patterns. </p>
<p>Those are my requirements for any proposal to introduce closures or first class functions into the Java language. I am prepared to reject any proposal that does not meet these two criteria.  If no proposal can satisfy these two criteria, then we shouldn&#8217;t add closures or first class functions. </p>
<p>So what are the proposals on the table, and how well do they meet these criteria?<br />
<span id="more-173"></span></p>
<h2><acronym title='concise instance creation expressions'>CICE</acronym></h2>
<p><acronym>CICE</acronym> has a number of extra rules:</p>
<p>&#8220;The construct is legal only if ClassOrInterfaceType represents a class or interface type with a single abstract method (a SAM type).&#8221; In other words, add a new method to an interface and the closure breaks. That&#8217;s not a problem because it&#8217;s already the case that adding a method to an interface breaks existing implementations. However, it&#8217;s a problem that we can only use closures with single-method interfaces. That&#8217;s exactly the sort of gotcha I want to avoid that will trip up people writing closures. </p>
<p>&#8220;Any visible local variable that is initialized or assigned exactly once in the enclosing scope, as well as any visible parameter to an enclosing method that is never otherwise assigned, is accessible but not assignable within the body of the CICE, whether or not it is explicitly qualified as final.&#8221; In other words,  adding a line that reassigns a variable, either in the closure or outside of it, can unexpectedly break things. This is a big problem. This is exactly the sort of gotcha I want to avoid.</p>
<p>&#8220;Any local variable that is explicitly qualified as public is accessible, and also assignable (unless also qualified as final), within the body of the CICE. Formal parameters and for-loop variables may not be qualified as public.&#8221; OK. We have to explicitly mark the variables we want to use in the closure. This seems like a slightly weaker version of only being able to use final variables, though why everything isn&#8217;t public by default I&#8217;m not sure. Furthermore the prohibition on public formal parameters (I think this means method arguments) and for loop indices seems unnecessarily confusing and gotcha prone.</p>
<p>There&#8217;s a second gotcha with this. The word <i>public</i> is being overridden to means something quite different from its usual meaning. These variables are not visible from outside the class. I&#8217;m sure this is being done to avoid introducing a new keyword, but it&#8217;s still added complexity for the language. <!-- Put it this way: do you really want to add an extra question for programmer job interviews? A good language should focus --></p>
<p>&#8220;Access to any other local variable or parameter from an enclosing scope is illegal within the body of a CICE.&#8221; It&#8217;s just not going to be obvious to people why they can use some variables in closures and not others. I think I&#8217;m coming to the conclusion that <em>implicit</em> final is a very bad thing, and a strong negative for any closure proposal. (Actually I&#8217;m coming around to the idea that implicit anything is a very bad idea, or at the least a code smell that warrants a second look.)</p>
<p>&#8220;It is, in many cases, technically feasible to infer types from the formal parameter list and method body of a CICE.  It is worth exploring the pros and cons of doing so.&#8221; I&#8217;m not sure exactly what&#8217;s being proposed here, but it sounds like more dangerous implicit code that will surprise and confuse. Java&#8217;s a strongly, statically typed language. Let&#8217;s keep it that way. Making one small part of it implicitly typed is just inconsistent and confusing. </p>
<h2><abbr>BGGA</abbr></h2>
<p>How does the <a href="http://www.javac.info/closures-v05.html"><abbr>BGGA</abbr> proposal</a> satisfy or fail these criteria? First I think it fails the syntax test. It is uglier than the CICE proposal, and I have the same reaction to it I first had to generics and Ruby: I don&#8217;t understand it. Despite ten+ years of Java experience I cannot just look at the code and figure out what it is doing. I&#8217;m sure I&#8217;d get used to it over time but what about people who are not full-time Java programmers? It is on the one hand too concise, preferring large amounts of punctuation over keywords. On the other hand it in effect introduces an infinite number of new keywords to the language. Reading code that uses this seems likely to be too complex. </p>
<p>What about gotchas? Here I think <abbr>BGGA</abbr> comes out on top. Once you decipher the syntax, there appear to be fewer special cases to worry about than with CICE. It is a more complete, cleaner proposal, though likely many gotchas won&#8217;t become apparent until I actually start to try writing code with this. A few things do bother me though.</p>
<p>First of all, I&#8217;m not sure I like that return returns from the enclosing scope rather than from the closure itself. That&#8217;s a surprise.</p>
<p>I also don&#8217;t like the implicit return at the end of the closure to get the value out, or that there&#8217;s no way to yield that value early. That&#8217;s a surprise too. It also makes the code harder to read. Either <code>return</code> should return from the closure, not the enclosing scope, or there needs to be a new <code>yield</code> keyword that returns from the closure. </p>
<p>&#8220;At runtime, if a break statement is executed that would transfer control out of a statement that is no longer executing, or is executing in another thread, the VM throws a new unchecked exception, UnmatchedNonlocalTransfer.&#8221; This is unnecessary. I think this is more like returning a value from a method when  that value is ignored and not stored. This should not cause an exception. The same is true for <code>continue</code> and <code>return</code>. The closure should silently exit when it complete and the enclosing scope no longer exists. Anything else violates the principle of least surprise, and exceptions are always surprising. It&#8217;s not as if the programmer actually needs to be told that the enclosing scope no longer exists, any more than they need to be told that the variable they&#8217;re returning from a method will be ignored. That&#8217;s an issue for the calling code, not the called code.</p>
<p>Like CICE, BGGA closure conversions only work with single method interfaces. That&#8217;s a gotcha.</p>
<h2>Bottom Line</h2>
<p>Both major current proposals flunk my criteria. If I&#8217;m forced to choose between them today, I choose neither: do not add closures to the Java language.</p>
<p>However, some of the problems may be fixable. In particular removing implicit final from <acronym>CICE</acronym> eliminates a lot of my objections there. Removing public local variables eliminates a few more. Is what&#8217;s left still useful and worth doing? I&#8217;m not sure.</p>
<p>The BGGA proposal is trickier to judge. I&#8217;d really like to see a fully written out version  of Neal Gafter&#8217;s talks on the subject. I&#8217;ve watched his video twice now, but it&#8217;s just not as easy to dig into video as text. Rather than writing the spec first, I think you need to write some code that uses the proposal. That&#8217;s the only way to see if the syntax makes sense. </p>
]]></content:encoded>
			<wfw:commentRss>http://cafe.elharo.com/blogroll/two-criteria-for-closures/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Why Hate the for Loop?</title>
		<link>http://cafe.elharo.com/blogroll/why-hate-the-for-loop/</link>
		<comments>http://cafe.elharo.com/blogroll/why-hate-the-for-loop/#comments</comments>
		<pubDate>Wed, 07 Feb 2007 15:26:54 +0000</pubDate>
		<dc:creator>Elliotte Rusty Harold</dc:creator>
				<category><![CDATA[Blogroll]]></category>

		<guid isPermaLink="false">http://cafe.elharo.com/java/why-hate-the-for-loop/</guid>
		<description><![CDATA[There&#8217;s one example that comes up sooner or later every time someone starts talking about closures. This time it&#8217;s from Bruce Tate on developerWorks: Listing 1. The simplest possible closure 3.times {puts "Inside the times method."} Results: Inside the times method. Inside the times method. Inside the times method. times is a method on the [...]]]></description>
				<content:encoded><![CDATA[<p>There&#8217;s one example that comes up sooner or later every time someone starts talking about closures. This time it&#8217;s from <a href="http://www-128.ibm.com/developerworks/java/library/j-cb01097.html">Bruce Tate on developerWorks</a>:</p>
<blockquote><p><b>Listing 1. The simplest possible closure</b></a><br />
<table border="0" cellpadding="0" cellspacing="0" width="50%">
<tbody>
<tr>
<td class="code-outline">
<pre class="displaycode">
3.times {puts "Inside the times method."}

Results:
Inside the times method.
Inside the times method.
Inside the times method.
</pre>
</td>
</tr>
</tbody>
</table>
<p>
<code>times</code> is a method on the <code>3</code> object. It executes the code in the closure three times. <code>{puts "Inside the times method."}</code> is the closure. It&#8217;s an anonymous function that&#8217;s passed into the <code>times</code> method and prints a static sentence. This code is tighter and simpler than the alternative with a <code>for</code> loop, shown in Listing 2:</p>
<p><a name="N100CE"><b>Listing 2: Looping without closures</b></a><br />
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody>
<tr>
<td class="code-outline">
<pre class="displaycode">
for i in 1..3 
  puts "Inside the times method."
end</pre>
</td>
</tr>
</tbody>
</table>
</blockquote>
<p>Personally I find the latter example simpler, clearer, and easier to understand. For one thing, when I see the word <i>times</i> suffixed to a number like 3 I expect multiplication, not action. But even if <code>times</code> were changed to a more reasonable method name such as <code>do</code> or <code>act</code>, I&#8217;d still prefer the <code>for</code> loop. (Perhaps what you really want here is &#8220;do 3 times&#8221;. That might really be clearer. )<br />
<span id="more-178"></span></p>
<p>I don&#8217;t know what it is some people have against <code>for</code> loops that they&#8217;re so eager to get rid of them. This isn&#8217;t the first or even the second time CS theorists have revolted against for loops (or equivalent). One advantage cited for RATFOR over traditional Fortran-77 was the ability to use index-less <code>while</code> loops instead of <code>DO</code> loops (Fortran&#8217;s equivalent of for). The Java Collections API brought us a confusing mass of iterators with weird modification behavior to avoid having to do something as simple and obvious as indexing our walks through a list. Then in Java 5 this wasn&#8217;t good enough. Some people were still ignoring iterators and stubbornly persisting in indexing their list traversals, so we got a whole new indexless <code>for ( String arg : args )</code> syntax. </p>
<p>What about a simple indexed loop offends people so much that they invent massive, complex syntax just to avoid it? Personally I find the indexed <code>for</code> loop syntax to be familiar and comforting. That&#8217;s why I deliberately designed XOM to support indexed access to the various components of the document tree. No iterators. No fancy loops. Just plain, old </p>
<pre><code>for (int i = 0; i &lt; element.getChildCount() ; i++) {
  Node child = element.getChild(i);
  //...
}</code></pre>
<p>The <code>times</code> syntax does avoid the explicit declaration and creation of a loop variable, though I&#8217;m sure that&#8217;s still happening behind the scenes and there&#8217;s no performance difference. Still,  it is nice that you don&#8217;t have the variable getting in your way if you don&#8217;t want it. Certainly in C and even in Java programmers are always <a title="opposite of debugging">enbugging</a> their code with wrongly scoped loop indices or fencepost errors. This makes indexless loops a nice feature for a language that has it from the get-go like Ruby. However I don&#8217;t think this is a big enough advantage to justify changing Java. </p>
<p>A much more serious concern is that indexless loops don&#8217;t have to be serial. That is, there&#8217;s nothing in a statement like <code>3.times {doSomething()}</code> that promises any particular order of execution. In fact, just maybe we can do all three actions at the same time. This enables parallel processing, and is going to be very important as multicore processors and multi-CPU systems become even more common. For example, consider the code to sum an array:</p>
<pre><code>double sum = 0;
for (int i = 0; i < array.length; i++) {
  sum += array[i];
}
</code></pre>
<p>The programmer probably doesn't care (and certainly shouldn't care) that we add <code>array[0]</code> to the sum before <code>array[5]</code>. If the array is large, we could actually execute this on eight separate CPUs, each summing an eighth of the array, and then add the subtotals at the end. A smart compiler could figure this out, but it's easier to do that if there's nothing in the code that refers to the loop index. </p>
<p>The <code>for</code> syntax implies serialization where you may not need it. The closure syntax doesn't necessarily guarantee the order of execution of the various statements. However, sometimes you actually do need a particular order of execution, or you need to refer to the loop index from within or outside of the code. For example, consider this simple loop that concatenates an array of strings named <code>args</code>:</p>
<pre><code>String s = "";
for (int i = 0; i < args.length; i++) {
  s += args[i];
}
</code></pre>
<p>String concatenation is not commutative, and it's really important that we add the strings in the proper order. A really smart compiler might still break this up into multiple threads. but it would have to be a lot more careful that the intended order was preserved.</p>
<p>Thus the closure syntax and the <code>for</code> syntax really aren't equivalent and closures can't replace <code>for</code> loops. They might supplement them, but this is only relevant if they really can be run on multiple processors simultaneously. In functional systems, this works because there are no side-effects. Thread safety is almost free. However, this isn't true in Java. In Java you have to think very carefully about thread safety, and typical closure code doesn't do that. Unless we have true functional programming, I'm not sure I see the point.</p>
<p>The current proposals for closures in Java all seem to still have sequential execution of code. For instance, the <a href="http://www.javac.info/closures-v05.html">BGGA proposal</a> makes a big point out of allowing <code>break</code> and <code>continue</code> inside closures, but what does that mean if the different iterations of the loop are in fact running on different processors at the same time? If the code is going to be sequential anyway, I prefer the style that makes that more obvious. The traditional indexed loop does that. A closure doesn't.  </p>
]]></content:encoded>
			<wfw:commentRss>http://cafe.elharo.com/blogroll/why-hate-the-for-loop/feed/</wfw:commentRss>
		<slash:comments>25</slash:comments>
		</item>
		<item>
		<title>Java as Lingua Franca</title>
		<link>http://cafe.elharo.com/blogroll/java-as-lingua-franca/</link>
		<comments>http://cafe.elharo.com/blogroll/java-as-lingua-franca/#comments</comments>
		<pubDate>Mon, 05 Feb 2007 13:39:03 +0000</pubDate>
		<dc:creator>Elliotte Rusty Harold</dc:creator>
				<category><![CDATA[Blogroll]]></category>

		<guid isPermaLink="false">http://cafe.elharo.com/java/java-as-lingua-franca/</guid>
		<description><![CDATA[When I travel I speak English. When I teach I speak Java, and for the same reason: it lets me be understood. When I need to teach cross-platform subjects like DOM or data structures to mixed language audiences, I can easily use Java to show examples and everyone can follow them, even if they&#8217;re not [...]]]></description>
				<content:encoded><![CDATA[<p>When I travel I speak English. When I teach I speak Java, and for the same reason: it lets me be understood.</p>
<p>When I need to teach cross-platform subjects like DOM or data structures to mixed language audiences, I can easily use Java to show examples and everyone can follow them, even if they&#8217;re not Java programmers. Everyone reads at least pidgin Java. Only C++ programmers can read C++. Only Ruby programmers can read Ruby. (Still better than Perl though. No one can read Perl, Perl programmers included.) </p>
<p>Of course, if you&#8217;re traveling in one area, it&#8217;s better to speak the native language if you can. French gets you farther in Lyons than English, but if you&#8217;re at an international conference  English is your only hope. If you&#8217;re at RubyConf, Ruby will get you far. However if you&#8217;re at OOPSLA or Software Development, Java is the way to go. </p>
<p>Java is the programmer&#8217;s lingua franca.<br />
<span id="more-172"></span></p>
<p>P.S. The <a href="https://www.cmpevents.com/SDe7/a.asp?Option=N">Call for Papers for Software Development Best Practices 2007</a> has just been posted. Aside from a token C++ track, it&#8217;s a pretty language neutral conference; and we don&#8217;t normally bother to check presenters&#8217; preferred programming language when deciding which presentations to accept. However, if you are showing code in a talk, I do recommend that you show it in Java.  </p>
]]></content:encoded>
			<wfw:commentRss>http://cafe.elharo.com/blogroll/java-as-lingua-franca/feed/</wfw:commentRss>
		<slash:comments>16</slash:comments>
		</item>
		<item>
		<title>CICE: Not So Nice</title>
		<link>http://cafe.elharo.com/blogroll/cice-not-so-nice/</link>
		<comments>http://cafe.elharo.com/blogroll/cice-not-so-nice/#comments</comments>
		<pubDate>Thu, 01 Feb 2007 13:38:34 +0000</pubDate>
		<dc:creator>Elliotte Rusty Harold</dc:creator>
				<category><![CDATA[Blogroll]]></category>

		<guid isPermaLink="false">http://cafe.elharo.com/java/cice-not-so-nice/</guid>
		<description><![CDATA[I&#8217;m still trying to wrap my head around closures, so I can decide if they&#8217;re a good idea or not; but there is one specific proposal I am willing to shoot down: Concise Instance Creation Expressions by Bob Lee, Doug Lea, and Josh Bloch. In fact, I think they shoot it down themselves pretty effectively [...]]]></description>
				<content:encoded><![CDATA[<p>I&#8217;m still trying to wrap my head around closures, so I can decide if they&#8217;re a good idea or not; but there is one specific proposal I am willing to shoot down:  <a href="http://docs.google.com/Doc.aspx?id=k73_1ggr36h">Concise Instance Creation Expressions</a> by Bob Lee, Doug Lea, and Josh Bloch. In fact, I think they shoot it down themselves pretty effectively without noticing what they&#8217;ve done. Here are their examples:<br />
<span id="more-171"></span></p>
<blockquote><p>  For example, here is the Java 5 code to start a thread whose <tt>run</tt> method<br />
  invokes a method named <tt>foo</tt>:</p>
<pre><code>    new Thread(new Runnable() {
        public void run() {
            foo();
        }
    }).start();
</code></pre>
<p>If we adopt this proposal, the following code would be equivalent:</p>
<pre><code>    new Thread(<b>Runnable(){ foo(); }</b>).start();
</code></pre>
<p>
  Here is the Java 5 code to sort a list of strings by length (from shortest to<br />
  longest):
</p>
<pre>    List&lt;String&gt;<string> ls = ... ;
   Collections.sort(ls, new Comparator&lt;String&gt;() {
        public int compare(String s1, String s2) {<
            return s1.length() - s2.length();
        }
    });
</string></pre>
<p>
  Here is the same code rewritten using the proposed syntax:
</p>
<pre><code>    List&lt;String&gt;<string> ls = ... ;
    Collections.sort(ls,<br />        <b>Comparator&lt;String&gt;(String s1, String s2){ return s1.length() - s2.length(); }</b>);
</string></code></pre>
</blockquote>
<p>Which is more legible to you? To me, the answer&#8217;s obvious: the anonymous inner class version that&#8217;s nicely indented. It&#8217;s not an ideal solution, but it&#8217;s better than the CICE alternative. The CICE alternative is a confusing mishmash of brackets, braces, and parentheses. Frankly, it&#8217;s starting to look like Perl. It&#8217;s shorter than the traditional approach, but that&#8217;s not a good thing. The redundancy and white space of the current syntax helps us read it, understand what&#8217;s going on, and makes it more legible. The compiler doesn&#8217;t need it, but we humans do. The CICE proposal lets the compiler fill in too much. The more that is implied by the code, the more the compiler fills in, the harder the code becomes to understand. Indeed the only way to explain or teach this stuff is to rewrite the example using traditional syntax, and tell students what&#8217;s the compiler is really doing is that.</p>
<p>We&#8217;ve already seen the confusion caused by the compiler writing code for us. Since Java 1.0, the compiler has helpfully filled in default constructors and default calls to <code>super()</code>, and this is a much simpler case. That&#8217;s probably a net benefit, but barely at best. Problems with default constructors trip up almost every student learning Java eventually; often more than once. Explicit code is good. Implicit code is bad. Explicit code you can read. Implicit code you have to remember. Reading is easy. Remembering is hard.</p>
<p>The second thing I don&#8217;t like about CICE is that it proposes a lot of weird rules about defaults. For instance, sometimes local variables will be final by default and sometimes they won&#8217;t. They&#8217;ll be final if they can be; that is if nothing assigns to them more than once. Then they can be used inside this new CICE expression. Otherwise they won&#8217;t be. However that&#8217;s going to cause massive debugging pain. Everything will be working fine, and then you add a simple statement like <code>x = x*2;</code> and suddenly the compiler starts spewing weird error messages that have nothing obvious to do with what you changed. I&#8217;m sure Bloch and Lea can figure this out in two minutes when it happens to them. I&#8217;m equally sure that my students and other not-as-expert programmers are going to waste many hours on this problem.</p>
<h2>Why I Don&#8217;t Like Anonymous Inner Classes</h2>
<p>It&#8217;s worth noting that my objections are grounded a little further back. I don&#8217;t really like anonymous inner classes all that much, and frankly I&#8217;m not that fond of regular inner classes either. They&#8217;re a constant source of annoyance because they never work quite like I expect due to all those silly rules about final local variables, <code>this</code> inside inner classes, and other arcana I can never quite remember. At this point I&#8217;ve given up on getting it right the first time. I just write the code I want to write, then debug the inevitable compiler error messages. I&#8217;ve gotten pretty good at that, but it&#8217;s still an annoyance.</p>
<p>When I teach Java, I tell my students not use inner classes of any kind; and indeed I forbid them from doing so on some of their homeworks. I find that if I let them use inner classes they just become a crutch to replace global variables. The students never learn  how to use methods to pass information and commands back and forth between objects. They just touch all the private parts directly, and they don&#8217;t know or care that behind the scenes the compiler is generating getters and setters. I do teach them what inner classes and anonymous inner classes look like, because they&#8217;ll have to read code other people have written using inner classes. However I recommend that they don&#8217;t use them themselves.</p>
<p>CICE is going the wrong way. Rather than removing the things that cause the confusion (inner classes) it&#8217;s adding more of them, and worse yet hiding them under the carpet where only the compiler sees them. I want code that&#8217;s more explicit and obvious, not less. </p>
<p>CICE is not syntax sugar. CICE is syntax cayenne pepper. It takes one of the ugly,  confusing (and unnecessary) parts of the Java language and makes it even uglier and more confusing. Possibly real closures might be better, and might indeed remove a lot of the ugliness that is inner classes. However CICE doesn&#8217;t do that. CICE makes matters worse, not better. </p>
]]></content:encoded>
			<wfw:commentRss>http://cafe.elharo.com/blogroll/cice-not-so-nice/feed/</wfw:commentRss>
		<slash:comments>13</slash:comments>
		</item>
	</channel>
</rss>
