15

I code Java for at least 5 years now and I really appreciate how the language works. When looking at new JVM languages (e.g. Scala, Clojure) there is a trend to more functional ways to code and this way has some major advantages.

Anyway, are there patterns to achieve a more functional style even when using Java or other pure OOP? And does this make sense in Java?

jimwise
  • 7,433
  • 1
  • 30
  • 32
Nils
  • 261
  • 2
  • 7
  • 3
    What major advantages do you see that you'd like to implement in Java? – pdr Jan 24 '13 at 23:54
  • 9
    Learn a functional language like Scala, Haskell, SML if you want to get familiar with the functional idioms. Then you can try to map them to Java. – Giorgio Jan 25 '13 at 09:00

5 Answers5

16

Functional programming has two primary qualities that define it - emphasis on immutable data and first-class functions. Both are - with some effort and within reason - achievable in Java.

You can certainly have immutable objects. Have the object state explicitly set through the constructor, do not expose setters and apply the final keyword to the fields. Whenever you would have a method modify the object's internal state, have it return a new instance with the updated state instead. An approach like this was presented in Real-World Functional Programming, a book containing examples of functional code in F# and corresponding code in C#. While C# is better suited for functional programming than Java, a similar approach could still be applied to Java.

When it comes to first-class functions, things get a bit more tricky. At the moment Java has a rather clumsy and verbose mechanism of emulating functions using anonymous nested classes, with a limited support for closures. While it's enough to write at least some pieces of code in a functional style, it would be a lackluster experience compared to using a proper functional language. There are Java libraries available, most notably guava, that introduce some of the functional programming concepts into Java, like immutable collections and some functional idioms. That would probably make the experience less gruesome - yet even the official documentation for guava states that functional idioms should only be used sparingly, as they often lead to code that is more verbose, less clear and less efficient than the corresponding imperative version.

The situation for Java is reportedly going to get better with the release of SE 8, set to include proper closures and lambda expressions, deferred from SE 7. Meanwhile you can try one of JVM's several functional languages and interop with Java when needed.

scrwtp
  • 4,532
  • 1
  • 24
  • 29
  • 2
    [Here's a link](http://stackoverflow.com/a/5444581/894284) that explains Java's current support for closures (it's not really true that it totally lacks closures). Also interesting is [what the author/maintainer of Guava has to say](http://code.google.com/p/guava-libraries/wiki/FunctionalExplained) about functional programming in Java: "As of Java 7, functional programming in Java can only be approximated through awkward and verbose use of anonymous classes [...] Excessive use of Guava's functional programming idioms can lead to verbose, confusing, unreadable, and inefficient code." –  Jan 25 '13 at 15:25
  • @MattFenwick: Interesting points. Edited the post to include them. Broke the links in the process ;) – scrwtp Jan 25 '13 at 19:16
  • Can you update third para in your answer given java 8 features? – user1787812 Nov 10 '17 at 12:10
  • @user1787812: I haven't been following Java for a couple years now - I'm happy if you or another community member edits this answer to include recent developments. If anything, my own taste has radicalized, and my advice when asked about FP in Java or C# would be - "don't, you'd be doing yourself a disservice, just use a proper language like Scala/F#/Clojure (depending on the context) instead". – scrwtp Nov 12 '17 at 15:55
5

Adding to what others have already said here, in Functional Programming there is a drive to separate side-effect producing / state changing code from functionally pure code and to make the separation explicit. This is achieved in e.g. Haskell through use of the IO and State Monads and in Clojure through refs.

In OOP state and state change are encapsulated in objects, so unless you go the immutable object route, this will likely be a bit more difficult to do.

Something that might help is to follow the Command/Query Separation Pinciple, which states that an operation should either be a command and cause side-effects, but not return anything, or it should be a query with a return value, causing no side-effects. Following this principle could help to get one into a more functional mindset, so far as managing side-effects is concerned.

EDIT

I don't know why this was initially down-voted; There's an article by John Carmack on Functional Programming in C++ which starts out similar what I've said above (sans the C/Q separation part) -- this is easily applicable to Java too.

paul
  • 2,074
  • 13
  • 16
4

Many of the Gang of Four design patterns are considered to be implementing functional concepts in an object oriented language.

Functional design patterns is a useful read. Also the series "Functional Thinking". Both from IBM.

A presentation (I haven't watched this to verify) on Functional Design Patterns is summarized as

Aino Vonge Corry reviews a number of well known design patterns showing that their implementation is simpler in functional languages because such languages have pattern-based constructs.

Within Java, closures can be implemented as local classes within a method and make for the ability to expand much more into the functional programing realm. Java 8 extends this functionality with lambdas.

So, to answer your question - many of the design patterns are implementing functional concepts already. And they do make sense in Java.

If all else fails, one can always invoke Greenspun's tenth rule to get whatever functional pattern you are after.

3

A good start is Neal fords: functional thinking.

You should then explore libraries like: Google guava , it's collections for essential abstractions like, function, predicate, map and filter operations.(google for functional programming with google collections, there are a couple of good blogposts)

There are couple of blogs about FP in java I read apocalisp.wordpress.com and I didn't regret it.

You may also explore functionaljava.org for more useful functional constructs like monoids.

Learning Haskell, Scala or Clojure is also a good idea but of course a bit more involved.

Good luck!

  • 2
    Why was this initially downvoted? (I voted it back up to 0.) It seems to be a great answer pointing to some good resources. A comment explaining the downvote would have been nice. – Tikhon Jelvis Jan 26 '13 at 21:39
  • Thanks Tikhon, I often post via the mobile site and editing support there is rather poor, let alone putting in multiple links. So people are picky about formatting issues. On content feedback, yes that's rarely done :/ – AndreasScheinert Jan 28 '13 at 12:23
0

Java 8 will introduce Lambdas which will be a gentle (or not so gentle for some) start for developers to get into functional programming with Java. Technically Java already has some functional programming capabilities, but they're very clumsy (anon inner classes).

Martijn Verburg
  • 22,006
  • 1
  • 49
  • 81