Mario has posted 14 posts at DZone. You can read more from them at their website. View Full User Profile

Is it Time for Functional Programming in Java?

09.14.2009
| 12152 views |
  • submit to reddit

Fuctional programming has existed for decades, but only in the last few years has it gained the attention it deserves, for a lot of very good reasons like:

  • it reduces code duplicarion
  • it improves readability
  • it allows better reuse
  • it facilitates multi-threading programming
  • it eliminates ugly programming by side-effects

Unfortunately Java doesn't natively allow you to take advantage of functional programming. It seemed for a couple of years that Java 7 was going to fill this lack by implementing the BGGA specification. But in the end they decided to keep BGGA out of Java 7, disappointing for the functional programming fan. This is one of the reasons why many Java programmers are migrating (or at least evaluating to migrate) toward more modern JVM compatible languages like Groovy and Scala. These languages allow developers to leverage the features of both object oriented and functional programming without losing the reliability and portability provided by a rock-solid and mature runtime environment like the JVM one.

Anyway, if you don't want to learn a completely new language (even if there could be some good reasons to do that as outlined  here) or more likely you are not allowed to use something different to Java, you could still introduce some functional programming techniques in your code. Indeed there are some tools and libraries available that allow you to do that in Java.

Probably the best known of these library is functionalJava which offers the possibility to write code following the BGGA specification already in Java 6. However this solution has, in my opinion, some important drawbacks like the needs to preprocess your code in order to translate the BGGA statements and the complete lack of support for the BGGA syntax in  IDEs.

Another tool that could serve to this purpose is functionalj. It has the advantage of not requiring any code translation, but it also looks far less powerful than functionalJava and doesn't seem to offer a satisfying generics support.

In the end, with its 2.0 release, lambdaj has provided a third option for functional programming in Java by allowing developers to define and use first-class functions, in a more readable DSL style. It seems to combine the pros of both the former libraries, but at the same time it presents some important limitations due to the heavy use of proxy made in its implementation.

To summarize if, like me, you feel the absence of functional programming in Java, these tools, despite not being perfect, can be a valuable replacement while waiting to finally see those features that will be available natively in plain Java.
Published at DZone with permission of its author, Mario Fusco.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Comments

Ricky Clarkson replied on Mon, 2009/09/14 - 5:47am

FunctionalJava does not require the use of BGGA syntax.

Runar Bjarnason replied on Mon, 2009/09/14 - 9:39am in response to: Ricky Clarkson

Too right. It's impossible for a library to require the use of BGGA.

Jacek Furmankiewicz replied on Mon, 2009/09/14 - 10:05am

Mario, first of all thank you for your heroic effort to introduce functional programming (in some form) to Java.

Having recently worked on an Erlang project, I can say I've understood the power of things such as list comprehensions, pattern matching and functional programming and I am starting to miss them when I get back to Java.

Nevertheless, your solution has some shortcomings, namely:

a) performance: as you mention yourself on averate it's around 4.5 times slower than imperative Java (up to 12 times slower on some benchmarks). That's a big issue for any perf-sensitive app.

b) the Closure effort is still somewhat clumsy: Closure0, Closure1, etc.

As I said, it's heroic what you've done, but there is only that many band aids that one can apply to Java. The language needs some major investment to bring it up to date, period.

I think what is much more likely is that once the Scala guys deliver the 2.8.0 rewrite of the Scala Eclipse plugin (which is supposed to provide IDE support on par with Java) a lot of the more senior developers will realize that it is at least 5 years ahead of where Java is and at least give it a shot. Without the need for any CGLib proxies and performance hits.

Regardless of this, I once again applaud your efforts on this. What lambdaj has done is quite an accomplishment. 

But if I want to really go functional, I think I'd just go full Scala instead.

 

Mario Fusco replied on Mon, 2009/09/14 - 10:43am in response to: Jacek Furmankiewicz

Thank you Jacek,

lambdaj, like the other projects I mentioned, just tries to mimic what any decent language of the XXI century should offer out of the box. Since these libraries are the result of the effort of some "heroic" programmers who are tired of this lack in a mainstream language like Java, of course they cannot provide an ideal solution. So I just tried to quickly summarize their respective pros and cons.

Actually I am an happy Scala programmer since more or less an year, but very often (as probably it happens to the biggest part of us) I am obliged to stuck programming in Java. In all these situation the use of those libraries (with all their defects and flaws) are the only possible way to have some sort of functional programming feature in Java.

Cheers
Mario

Mike P(Okidoky) replied on Mon, 2009/09/14 - 11:21am

Mario, I had some initial thoughts, and I'm trying to see the advantages of functional programming. Realize that my experiences are mainly Java (OO), Javascript, and PHP. A few years back I created a web server with Javascript to process web pages.I *guess* that was functional programming. The strategy was somewhat similar to the way PHP is handled. A stream of statements get run on every web page load. The least amount of state is remembered on each page load, and everything allocated is freed each time.

Based on that:

  • it reduces code duplicarion
In OO you create a class or set of classes for each logical task. When implemented cleanly, you don't end up creating similar functions in other places. With functional programming it's easier to start duplicating code. What am I missing?
  • it improves readability
The other way around I think.
  • it allows better reuse
Again, the other way around I think.
  • it facilitates multi-threading programming
Not having state by default helps beginner programmers reduce multithreading issues, but in OO you could easily create a "Job" class of sorts upon each execution, each time with a fresh state. In fact, you could load it up nicely with all the data it needs.
  • it eliminates ugly programming by side-effects

For anything medium or even with slight complexity, in my experience, you'll easily end up with a spaghetti mess (based on my PHP experiences). I've combatted that by creating classes in PHP to start nicely categorizing and localizing functions along with the data it needs, instead of having things spread around like a wild fire.

Why is functional programming attactive to some? Is this not more a case of people not knowing how to apply OO effectively?

 

Jacek Furmankiewicz replied on Mon, 2009/09/14 - 11:49am in response to: Mike P(Okidoky)

Here's a blob of Erlang code that saves some object data into their Mnesia object database:

SaveFun = fun() ->

      ...do some DB saving logic here, e.g. insert some new records

               end,

mnesia:transaction(SaveFun).

 The last part "mnesia:transaction(SaveFun)" is the important one here. You are passing a function instance to another function as an argument. That function takes care of all the regular logic (open transaction, commit it, rollback in case of error, etc.). It's that type of reusability that is very useful.

Sure, you can do exactly the same by passing an instance of Runnable to a method, but it's 2-3 lines more of boilerplate code. It adds up.

Things get even more concise with closures combined with list comprehensions (another Erlang example):

[net_adm:ping(NodeName) || NodeName <- rpc:call(MasterNode,erlang,nodes,[])];

What this code does is call a remote Erlang node, asking it for its list of cluster nodes it knows. Then it passes that list into a list comprehension which executes a closure (in this case a ping of that node that establishes a connection to i.

Let's try to write this code in typical iterative Java

List<Node> nodes = masterNode.getNode();

for(Node node : nodes) {

    SomeNetworkLibrary.ping(node);

 As I said, it quickly adds up. The ability to pass functions into other functions as arguments allows to build really nice tight, generic algorithms and the ability to do list comprehensions cuts down on number of lines of code significantly.

Now, that is said and done Erlang has a lot of other issues (it denies OO and makes everything immutable, so complex nested record manipulations are a major pain). But being exposed to it opened my eyes to what Scala tries to do, i.e. bring the best of both functional and OO programming together.

Mike P(Okidoky) replied on Mon, 2009/09/14 - 12:15pm in response to: Jacek Furmankiewicz

> you can do exactly the same by passing an instance of Runnable to a method

Or an appropriate interface with a return value and possibly other methods to help facilitate the two way communication.

Both examples look very foreign and compressed.

It seems today's fad is about making code as compressed as possible. We're seeing example after example of people trying to sell languages that do more with less characters. I can't see how some of the colleagues I've worked with in the past are going to be effective programmers. They're not going to understand what you write, and the mess they contribute back would probably have to be re-written, re-compressed, by you.

I think we should all change today's trend. We should try to develop languages that allows you to comprehend what it does in the least amount of time possible. I'm not saying that Java does that. I think Java needs to evolve as much as the next guy. But I'm not liking where the braincycles have gone over the last while.

Jacek Furmankiewicz replied on Mon, 2009/09/14 - 12:26pm in response to: Mike P(Okidoky)

Foreign, yes. Compressed yes. It's a different language, obviously.

But once you get used to it (took me 2 weeks or so) then it reads as naturally as your more verbose Java code.

As I said, I didn't get into functional programming because it's the latest fad, but because I actually did a project in a language that supports it. Now I find myself thinking in this way when I write Java code and missing this type of concise, reusable constructs.

 

Mike P(Okidoky) replied on Mon, 2009/09/14 - 1:57pm in response to: Jacek Furmankiewicz

With fad I meant the drive to compress. I'm think it's good to not have to express things that are obvious, but I think going overboard on verbosity reduction is counter productive, especially in team settings where not everyone is as "gifted".

But more about the notion of functional programming. How about an example, and in rough outlines how you would go about implementing something using functional programming methods, vs an OO method...

Bryan Taylor replied on Mon, 2009/09/14 - 3:16pm

I think scala is the answer. It takes longer to morph java into a functional language than it does to simply change to a functional language.

Stefan Zobel replied on Mon, 2009/09/14 - 3:22pm in response to: Mike P(Okidoky)

To my mind, working with functions is not so much about conciseness but about composability of functionality. Tony Morris has a good blog entry on this point: http://dibblego.wordpress.com/2009/05/13/the-loc-misintegration/

Jacek Furmankiewicz replied on Mon, 2009/09/14 - 3:39pm in response to: Bryan Taylor

I agree. All I want is a usable Eclipse plugin (that handles mixed Java/Scala projects with ease) and we're off running with Scala in a month. No more complaining from me about Sun wasting resources on JavaFX when their crown jewel needs some serious TLC instead.

 

Mario Fusco replied on Mon, 2009/09/14 - 4:00pm in response to: Stefan Zobel

Hi Stefan and thank you for the Bloch's presentation :)

composability --> reusability --> less code duplication --> more conciseness

Ricky Clarkson replied on Mon, 2009/09/14 - 4:06pm in response to: Mike P(Okidoky)

I think you've got quite confused. Functional programming isn't the same thing as procedural programming, which is what you were writing in JavaScript and PHP.

Mario Fusco replied on Mon, 2009/09/14 - 4:13pm in response to: Jacek Furmankiewicz

I totally agree. The last JavaOne has been mainly a slalom to try to avoid the useless JavaFX presentations :(

I also tried the Scala plugin for IntelliJ and honestly it disappointed me as well.

As I said I love Scala. Once again the tools I introduced in my article are intended to be used only when you are obliged to use Java. Unfortunately it happens to me about 80% of time and I am pretty sure it happens more or less the same to the biggest part of us.

Stefan Zobel replied on Mon, 2009/09/14 - 4:24pm in response to: Mario Fusco

Hello Mario, you are welcome ;)

Your cause-and-effect chain is also correct, of course.

I simply wanted to stress that, IMO, Mr.Morris hits the mark when he writes "If we were to discuss the benefits of programming languages, we might discuss how amenable they are to compositional properties, rather than how many lines of code it takes to perform a particular task."
This is the real benefit of FP - not some saved key strokes.

Mike P(Okidoky) replied on Mon, 2009/09/14 - 5:00pm

I'd like to pick up a book on programming paradigms, can anyone recommend a good book?

  • Programming Languages: Principles and Paradigms
  • Programming Language Concepts Paradigms
  • Programming Language: Principles and Paradigms
  • Separating Data from Instructions: Investigating a New Programming Paradigm

?

 

Stefan Zobel replied on Mon, 2009/09/14 - 5:16pm in response to: Mike P(Okidoky)

I found this one particularly easy to read:

"Concepts in Programming languages", by John C. Mitchell

Christian Maslen replied on Mon, 2009/09/14 - 5:39pm

I'd like to pick up a book on programming paradigms, can anyone recommend a good book?
  • Programming Languages: Principles and Paradigms
  • Programming Language Concepts Paradigms
  • Programming Language: Principles and Paradigms
  • Separating Data from Instructions: Investigating a New Programming Paradigm

Programming Language Pragmatics III by Michael L. Scott..

It's 5 star rating is well deserved.

Christian.

Liam Knox replied on Mon, 2009/09/14 - 8:56pm in response to: Jacek Furmankiewicz

I agree lambdaj is neat but could not see personal usage or sign off given the downsides. Given a change in constructor signature or introduction of a final to the class declaration could automatically start blowing up production code I would think this is too much risk vs reward compared to just using google collections and working with existing idioms.

I agree functional-wise you are better going straight to Scala if you have that option , but I implore the Java community, Sun , Oracale etc to get some JSR approved that addresses this concern properly in Java.

Given the amount of systems out there it would have massive benefits. The adoption of Scala will come but will not be anywhere near Java in I would say the next 5-10 years. I didnt completelty like BGGA but functionaly it was good and I would work with it. Blochs proposal just seems to short cut the syntax and you would end up declaring millions of interfaces in certain use cases ( see Forkjoin ).

Pavel Lahoda replied on Tue, 2009/09/15 - 1:59am

I don't know if it is time for functional programming, but for me the clear priority would be to get rid of "hardwired" strings from the language (such as described there : http://incubator.apache.org/empire-db/empiredb/stringfree.htm)

Armin Ehrenreich replied on Tue, 2009/09/15 - 2:04am

Different computer languages follow different concepts. The different concepts have different advantages and disadvantages, therefore they exist. Java is an object oriented language and was very successful with its concept and I am sure it will stay that way for a long time. No need to destroy that tool by creating a maximal ugly mixture of different concepts. This will look like a botoxed old lady that still want to dance with the kids. Look what they have done to C#. It looks like a chaotic christmas tree of redundant features. With forcing functional programming into Java, additionally many developers that don't want or can't use this paradigm will be alienated. And this is without need. The solution is so easy. Sun/Oracle has simply to support Scala officially. Then we have a modern, well designed language for functional parts of a project and good, clear and proven Java for the majority of code. Everyone has what he needs.

Christian Maslen replied on Tue, 2009/09/15 - 6:27pm in response to: Armin Ehrenreich

... Look what they have done to C#. It looks like a chaotic christmas tree of redundant features.


Have a look at what Fluent have done for NHibernate with lamdas. If you think this is chaotic compared to the xml or even the attributes/annotations then I guess we have a different sense of aesthetics. It gives you compile time and edit time (via the IDE) validation and is easy for any C#er to understand.

Christian.

Mike P(Okidoky) replied on Wed, 2009/09/16 - 12:08pm

Ok, I'm on board now with the Scala thing. It's got all those modern feature. I particularly like traits/mixins, multiple inheritance (I absolutely *hated* missing that since I left C++ 10 years ago).

I see great value in functional programming, and the rest of the features.

Scala doesn't suffer from a fanboy syndrome (eg. Ruby, Python) from what I can gage so far, and doesn't go reflection happy like Groovy.

Clearly, we have a winner here. Ok, so what's with the lack of Eclipse / Netbeans support? Is it or is it not possible to edit these files, debug them, and benefit from all those nifty source code management tools?

Back to the original topic - should we have functional programming in Java? Well, closures fell apart for Java 7, and one of Java's strong values is the fact that it's kept simple enough where mediocre programmers can remain effective. Perhaps there's pressure to keep Java accessible by cheap off-shore programmers from big companies (politics is preventing Java from evolving).

But who cares, Scala is just another, better javac.

I'm curious which language would be Scala's closest competitor in terms of being the best language?

David Walend replied on Wed, 2009/09/16 - 9:33pm

Any opinion of clojure? http://clojure.org/

Mike P(Okidoky) replied on Wed, 2009/09/16 - 11:32pm

Clojure, another language to investigate. At first glance, people seem to like Scala better.

But is Scala functional (enough) (no pun)?

http://enfranchisedmind.com/blog/posts/scala-not-functional/

Groovy looks done.

Rumors of Ruby based architectures getting replaced with Scala.

Python can't stand.

Any other contenders?

Armin Ehrenreich replied on Thu, 2009/09/17 - 3:56am in response to: David Walend

Clojure looks to me like a Lisp dialect (but I haven't tried it, to be honest). And Lisp was around forever, but was never widely used outside university departments. There must be some reason. Maybe the total requirement of functional programming doesn't fit with the way people think. With Scala you can choose. You can program as in Java but do functional programming where it fits. But maybe Clojure is a nice counterpart to F# from the MS side of the world.

Christian Harms replied on Thu, 2009/09/17 - 6:15am

Interessing, that someone say javascript/python is prodecural not functional.

 Both languages have some elements and the possibility to do it. Look at united-coders.com/ for python. In javascript there are some libs (Functional) and some extensions in newser browsers.

Jacek Furmankiewicz replied on Thu, 2009/09/17 - 7:29am in response to: Mike P(Okidoky)

Problem with languages like Clojure (and Erlang) is that by taking away OOP and making everything immutable they make definining and manipulating complex object graphs (e.g. business entities) quite painful.

Erlang looked great to me...until I had to manipulate an object graph (since Erlang does not have objects we had to use nested records)...the code to do it was horrendous (since everything is immutable, even the slighltest change means you have to carefully copy the whole object graph at every modification). The resulting code was 10 times the size of the equivalent Java code.

That's why Scala looks so promising: OOP for business entities and as much functional programming for the actual business functionality. At least that's what's attracting me to it.

Unfortunately, the sad part is that even the new Scala Eclipse plugin is in a sad state...I just tried the nightly build last night and even something basic like code completion on Java classes is not working properly.

Scala really has an opportunity right now to make some inroads, but they have to make dev tools their primary focus, even over the language itself.

P.S. Python is really nice actually...did some minor work in it and it was quite enjoyable. Not sure why you dislike it so much. The whitespace issue for me was actually quite intuitive, makes for very readable code.

Martin Wildam replied on Tue, 2009/09/22 - 7:15am

I don't have an idea why the there is so much rumour now about functional programming.

Given the sample from http://en.wikipedia.org/wiki/Functional_programming#Coding_styles I can only say that it is far from my experience in practice. In very few cases I can find such clear (mathematic) relations.

What functions are used to manipulate an item before adding to target or returning as output usually depends on a series of conditions so it would not be efficient to write a code in a functional way.

I am pretty sure that a lot of Java programmers did excessive use of objects and classes in solutions that could have been easier with less objects and classes using just a few static classes with the appropriate methods dealing with the data.

So however am trying to find out how people see the big advantage in functional programming (style), I can't really find it. Maybe someone can help me se it...

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.