Closures and Lambdas
Over the past year I have been programming heavily in C#. This experience involved working on a few reasonably large projects and has let me get a good feel for lambda expressions and closures.
For those who do not know, a lambda expression is an anonymous function. Closures are functions where variables not defined in the function parameter-list but accessible in the environment where the function is defined. Lambda expressions in C# obviously define lambdas, but can also define closures. In saying this, it is important to note that closures are not lambdas.
Prior to using lambda expressions in C# I had spent most of my time programming in Java and Pawn. Neither of these languages support lambda expressions and now when I write code in these languages it hurts. Trying to recreate the simplicity that lambdas provide is impossible and in Java there is a lot of noise in defining reusable functions. Reusable functions in Java are usually defined as Functors. The difference is made apparent in my Honours Project where it is necessary write code like this:
This method of doing things required that I define an additional interface and also define classes which implement it and provide the behaviour necessary. These additional classes contain a lot of boilerplate code and (usually) one out of five lines defines the difference. If this setup was defined in a language which supported lambdas, such as C# then I would be writing something like this:
This is a lot simpler. In terms of line count (without comments) the C# example is 40% smaller than the Java example. I imagine the difference is much greater in my current code base which defines several more of these
VoiceMethods. Using lambdas is much more concise and to the point and I could now even argue that my original reasons for the
VoiceMethodFactory are now void. The reason I created the factory was to move this anonymous class definition noise away from another part of my system.
Java 8 is going to support lambdas and closures as part of Project Lambda. It is unfortunate however that Android developers may not get to use lambda expressions in their Java code for a little while yet. This is because Android does not use the official Java implementation. Instead Android uses Apache Harmony, an open-source implementation of Java, due to licensing issues between Sun and Google.