This page shows the source for this entry, with WebCore formatting language tags and attributes highlighted.

Title

Java 8

Description

<img style="background-color: white" attachment="java8_logo.png" align="left"><n>This article discusses and compares the initial version of Java 8 and C# 4.5.1. I have not used Java 8 and I have not tested that any of the examples---Java or C#---even compile, but they should be pretty <i>close</i> to valid.</n> Java 8 has finally been released and---drum roll, please---it has closures/lambdas, as promised! I would be greeting this as champagne-cork--popping news if I were still a Java programmer.<fn> As an ex-Java developer, I greet this news more with an ambivalent shrug than with any overarching joy. It's a sunny morning and I'm in a good mood, so I'm able to suppress what would be a more than appropriate comment: "it's about time". Since I'm a C# programmer, I'm more interested in peering over the fence at the pile of goodies that Java just received for its eighth birthday and see if it got something "what I ain't got". I found a concise list of new features in the article <a href="http://ahmedsoliman.com/2014/03/26/will-java-8-kill-scala/" author="Ahmed Soliman">Will Java 8 Kill Scala?</a> and was distraught/pleased<fn> to discover that Java had in fact gotten two presents that C# doesn't already have. As you'll see, these two features aren't huge and the lack of them doesn't significantly impact design or expressiveness, but you know how jealousy works: Jealousy doesn't care. Jealousy is. I'm sure I'll get over it, but it will take time.<fn> <h>Default methods and static interface methods</h> Java 8 introduces support for <i>static methods on interfaces</i> as well as <i>default methods</i> that, taken together, amount to functionality that is more or less what extensions methods brings to C#. In Java 8, you can define static methods on an interface, which is nice, but it becomes especially useful when combined with the keyword <c>default</c> on those methods. As defined in <a href="http://docs.oracle.com/javase/tutorial/java/IandI/defaultmethods.html" source="Java Tutorials">Default Methods</a>: <bq>Default methods enable you to add new functionality to the interfaces of your libraries and ensure binary compatibility with code written for older versions of those interfaces.</bq> In Java, you no longer have to worry that adding a method to an interface will break implementations of that interface in other jar files that have not yet been recompiled against the new version of the interface. You can avoid that by adding a default implementation for your method. This applies only to those methods where a default implementation is possible, of course. The page includes an example but it's relatively obvious what it looks like: <code> <b>public interface</b> ITransformer { <b>string</b> Adjust(<b>string</b> value); <b>string</b> NewAdjust(<b>string</b> value) { <b>return</b> value.Replace(' ', '\t'); } } </code> How do these compare with extension methods in C#? Extension methods are nice because they allow you to quasi-add methods to an interface without requiring an implementor to actually implement them. My rule of thumb is that any method that can be defined purely in terms of the public API of an interface should be defined as an extension method rather than added to the interface. Java's default methods are a twist on this concept that addresses a limitation of extension methods. What is that limitation? That the method definition in the extension method can't be overridden by the actual implementation behind the interface. That is, the <i>default</i> implementation can be expressed purely in terms of the public interface, but perhaps a specific implementor of the interface would like to do that plus something more. Or would perhaps like to execute the extension method in a different way, but only for a specific implementation. There is no way to do this with extension methods. Interface default methods in Java 8 allow you to provide a fallback implementation but also allows any class to actually implement that method and override the fallback. <h>Functional Interfaces</h> Functional interfaces are a nice addition, too, and something I've wanted in C# for some time. <a href="http://en.wikipedia.org/wiki/Erik_Meijer_(computer_scientist)">Eric Meijer</a> of Microsoft doesn't miss an opportunity to point out that this is a must for functional languages (he's exaggerating, but the point is taken). Saying that a language supports functional interface simply means that a lambda defined in that language can be assigned to any interface with a single method that has the same signature as that lambda. An example in C# should make things clearer: <code> <b>public interface</b> ITransformer { <b>string</b> Adjust(<b>string</b> value); } <b>public static class</b> Utility { <b>public static void</b> WorkOnText(<b>string</b> text, ITransformer) { // Do work } } </code> In order to call <c>WorkOnText()</c> in C#, I am <i>required</i> to define a class that implements <c>ITransformer</c>. There is no other way around it. However, in a language that allows functional interfaces, I could call the method with a lambda directly. The following code looks like C# but won't actually compile. <code> Utility.WorkOnText( "Hello world", s => s.Replace("Hello", "Goodbye cruel") ); </code> For completeness, let's also see how much extra code it is do this in C#, which has no functional interfaces. <code> <hl><b>public class</b> PessimisticTransformer : ITransformer { <b>public string</b> Adjust(<b>string</b> value) { <b>return</b> value.Replace("Hello", "Goodbye cruel"); } }</hl> Utility.WorkOnText( "Hello world", <hl><b>new</b> PessimisticTransformer()</hl> ); </code> That's quite a huge difference. It's surprising that C# hasn't gotten this functionality yet. It's hard to see what the downside is for this feature---it doesn't seem to alter semantics. While it is supported in Java, there are other restrictions. The signature has to match exactly. What happens if we add an optional parameter to the interface-method definition? <code> <b>public interface</b> ITransformer { <b>string</b> Adjust(<b>string</b> value<hl>, ITransformer additional = <b>null</b></hl>); } </code> In the C# example, the class implementing the interface would have to be updated, of course, but the code at calling location remains unchanged. The functional interface's definition <i>is</i> the calling location, so the change would be closer to the implementation instead of more abstracted from it. <code> <b>public class</b> PessimisticTransformer : ITransformer { <b>public string</b> Adjust(<b>string</b> value<hl>, ITransformer additional = <b>null</b></hl>) { <b>return</b> value.Replace("Hello", "Goodbye cruel"); } } // Using a class Utility.WorkOnText( "Hello world", <b>new</b> PessimisticTransformer() ); // Using a functional interface Utility.WorkOnText( "Hello world", <hl>(</hl>s<hl>, a)</hl> => s.Replace("Hello", "Goodbye cruel") ); </code> I would take the functional interface any day. <h>Java Closures</h> As a final note, Java 8 has finally acquired closures/lambdas<fn> but there is a limitation on which functions can be passed as lambdas. It turns out that the inclusion of functional interfaces is a workaround for not having first-class functions in the language. Citing the article, <bq>[...] you cannot pass any function as first-class to other functions, the function must be explicitly defined as lambda or using Functional Interfaces</bq> While in C# you can assign any method with a matching signature to a lambda variable or parameter, Java requires that the method be first assigned to a variable that is <iq>explicitly assigned as lambda</iq> in order to use. This isn't a limitation on expressiveness but may lead to clutter. In C# I can write the following: <code> <b>public string</b> Twist(<b>string</b> value) { <b>return</b> value.Reverse(); } <b>public string</b> Alter(<b>this string</b> value, Func<<b>string</b>, <b>string</b>> func) { <b>return</b> func(value); } <b>public string</b> ApplyTransformations(<b>string</b> value) { <b>return</b> value.Alter(Twist).Alter(s => s.Reverse()); } </code> This example shows how you can declare a <c>Func</c> to indicate that the parameter is a first-class function. I can pass the <c>Twist</c> function or I can pass an inline lambda, as shown in <c>ApplyTransformations</c>. However, in Java, I can't declare a <c>Func</c>: only functional interfaces. In order to replicate the C# example above in Java, I would do the following: <code> <b>public</b> String twist(String value) { <b>return new</b> StringBuilder(value).reverse().toString(); } <b>public</b> String alter(String value, <hl>ITransformer transformer</hl>) { <b>return</b> <hl>transformer.adjust</hl>(value); } <b>public</b> String applyTransformations(String value) { <b>return</b> <hl>alter(alter(value, s -> twist(s)), s -> StringBuilder(s).reverse().toString();</hl> } </code> Note that the Java example cannot pass <c>Twist</c> directly; instead, it wraps it in a lambda so that it can be passed as a functional interface. Also, the C# example uses an extension method, which allows me to "add" methods to class <c>string</c>, which is not really possible in Java. Overall, though, while these things feel like deal-breakers to a programming-language snob<fn>---especially those who have a choice as to which language to use---Java developers can rejoice that their language has finally acquired features that both increase expressiveness and reduce clutter.<fn> As a bonus, as a C# developer, I find that I don't have to be so jealous after all. Though I'd still really like me some functional interfaces. <hr> <ft>Even if I were still a Java programmer, the champagne might still stay in the bottle because adoption of the latest runtime in the Java world is <i>extremely</i> slow-paced. Many projects and products require a specific, older version of the JVM and preclude updating to take advantage of newer features. The .NET world naturally has similar limitations but the problem seems to be less extreme.</ft> <ft>Distraught because the features look quite interesting and useful and C# doesn't have them and pleased because (A) I am not so immature that I can't be happy for others and (B) I know that innovation in other languages is an important driver in your own language.</ft> <ft>Totally kidding here. I'm not insane. Take my self-diagnosis with a grain of salt.</ft> <ft>I know that lambdas and closures are not by definition the same and I'm not supposed to use the interchangeably. I'm trying to make sure that a C# developer who reads this article doesn't read "closure" (which is technically what a lambda in C# is because it's capable of "closing over" or capturing variables) and not understand that it means "lambda".</ft> <ft>Like yours truly.</ft> <ft>Even if most of those developers won't be able to use those features for quite some time because they work on projects or products that are reluctant to upgrade.</ft>