Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

let's assume I have a task to create a Set of class names. To remove duplication of .getName() method calls for each class, I used org.apache.commons.collections.CollectionUtils and org.apache.commons.collections.Transformer as follows:

Snippet 1:

Set<String> myNames = new HashSet<String>();
CollectionUtils.collect(
        Arrays.<Class<?>>asList(My1.class, My2.class, My3.class, My4.class, My5.class),
        new Transformer() {
            public Object transform(Object o) {
                return ((Class<?>) o).getName();
            }
        }, myNames);

An alternative would be this code:

Snippet 2:

Collections.addAll(myNames, My1.class.getName(), My2.class.getName(), My3.class.getName(), My4.class.getName(), My5.class.getName());

So, when using functional programming approach is overhead and when it's not and why?

Isn't my usage of functional programming approach in snippet 1 is an overhead and why?

share|improve this question
5  
First snippet is not really functional as CollectionUtils.collect seems to be modifying myNames object state. –  Den Oct 3 '12 at 8:12
1  
I think the title is too generic: the pattern you are implementing involves mapping objects from a list to a list whereas from the title it seems you are asking about functional programming in general. –  Giorgio Oct 3 '12 at 8:33
    
"CollectionUtils.collect seems to be modifying myNames object state.": what suggests you this? –  Giorgio Oct 3 '12 at 8:38
1  
BTW: I'd personally use for (Class<?> c : classes) { myNames.add(c.getName()) } so I won't have to duplicate getName() –  scarfridge Oct 3 '12 at 8:56
1  
Not really answering your question, but I feel compelled to give a link where John Carmack discuss the pro's and con's of using functional programming with an imperative language (in his case C++ but it translates fine into Java): altdevblogaday.com/2012/04/26/functional-programming-in-c –  S4M Oct 3 '12 at 12:22
show 3 more comments

5 Answers

Functional approach usually gives you a better looking, shorter code. But dealing with immutability may result in a performance penalty. I think first snippet looks like overhead because functional syntax in Java is too verbose.

share|improve this answer
1  
"because ... syntax in java is too verbose." Not just functional syntax. No offence to Java folks, it's a great language for anyone who really likes typing ;p –  glenatron Oct 3 '12 at 8:49
5  
@glenatron: Java's verbosity is a feature: I have spent literally weeks trying to track down bugs in more concise languages, and their conciseness was getting in the way because it was much more difficult to understand what the original developer actually meant. So sometimes I really prefer Java's verbosity to other languages' conciseness. –  Giorgio Oct 3 '12 at 8:57
1  
@Giorgio also, practically, how much of our time is actually spent typing? Programmers type really fast, so even Java's war-and-peace-like coding approach isn't that much of a drag in real terms. Still, given that I mostly write C#, which is basically terser Java, I am always happy to give my cross-platform brothers and sisters a ribbing. –  glenatron Oct 3 '12 at 9:14
2  
@glenatron: That's exactly what I wanted to say. Consider also that automatic code completion saves you much of the typing. Also, some very concise languages tend to hide too many details behind very short statements: I have seen very nasty bugs emerging in this way because not even the original author of the code knew what was going on. The fact that Java forces you to think about the complexity of your code is an advantage some times. In Java one can achieve conciseness by designing proper classes and composing them, not by using some remote language feature that only the gurus understand. –  Giorgio Oct 3 '12 at 9:24
add comment

As others noted, you can't really use a functional approach in Java, because it is way too verbose and simply lacks a lot of necessary features. So the resulting code will usually look more complex and ugly. Sometimes it is still worth it—because the alternative would include even more duplication and/or other ugliness—sometimes it isn't. You need to decide on a case by case basis. Try out different approaches and choose the one resulting in the cleanest, simplest code. And don't bother too much with labels. :-) Writing code in "functional" style is not superior per se than any other style—only if your code is actually shorter, cleaner, easier to maintain and extend and/or more efficient in some significant way.

This brings us to another important point. Even if you managed to implement some piece of code in a "functional" way really succinctly, you need to look at it from the point of view of the future maintainers. Will an average Java programmer understand your piece of code if it is so different from the mainstream and well-known Java idioms? Most likely not, which increases the probability of them introducing bugs during future development/maintenance. Your code must have very strong and provable advantages to counterbalance this, and you need to document it well.

share|improve this answer
    
"Even if you managed to implement some piece of code in a 'functional' way really succinctly ... Will an average Java programmer understand your piece of code?" - can you give an example of such code? I mean it is not Perl or BF language :). –  Den Oct 3 '12 at 9:14
    
@Den, that was rather a thought experiment at this stage :-) I am looking forward to get Java8 and lambdas... In the meantime, as suggested by others, one could try mingling in bits of e.g. Scala code into Java projects. However, with Scala's significantly different syntax and style, and less mainstream status, my point above applies even stronger. –  Péter Török Oct 3 '12 at 10:13
    
yeah, Scala is a different story... F# can definitely be hard to read for new people. –  Den Oct 3 '12 at 10:53
    
@Den you might consider types that act as callbacks/receivers as an example. They can be provided inline, anonymously, but even in cases where their use is functionally correct and they perform a minor task, like simply returning the class name as in the first snippet, their declaration is unavoidably verbose and whichever style guide you use will immediately single out chunks that receive unnecessary attention and give rise to queer feelings. –  Filip Dupanović Oct 3 '12 at 11:06
    
+1 for "Will an average Java programmer understand your piece of code if it is so different from the mainstream and well-known Java idioms?" I totally agree, and this is also one reason why I think Java should not be extended with some functional features (just a marketing strategy to keep up with the cool kids): Java is a great language for OOP and should stay as it is. In order to do proper functional programming one should switch to a language that was designed for it from the beginning (Haskell, Scala, Clojure, to name a few). –  Giorgio Jun 28 '13 at 23:47
add comment

Java was not designed for functional programming and so, while you can use a functional programming style in Java (immutable state, recursion, function composition, high-order functions, ...), you will often miss certain features that facilitate functional programming (ad-hoc syntactic constructs, currying, function composition operator, tail-call optimization, ...).

Therefore, even though a functional style in Java can make your code (sometimes) more readable or (more often) more robust, if you really want to use it heavily you'd better use a language that was designed for it. For the JVM you can use Scala or Clojure (here is a short article, that also discusses Groovy). Otherwise, you can try Haskell, Common Lisp, Scheme, F#, Ocaml, and others.

share|improve this answer
add comment

Theoretically a functional approach is simpler, more versatile, more verifiable, and easier to understand at-a-glance. If what you end up with doesn't hit at least one of those goals, then perhaps it's not the best approach for your circumstances.

Note that functional is, as previously mentioned, a bit of a reach for Java. But not for the JVM. Scala and Groovy are a bit more flexible in that regard and allow you to express functional concepts much more succinctly. And if you want to to all-out functional, there's always Clojure. All of these target the JVM and should integrate reasonably well into an existing Java project.

If you're stuck with a Java environment (JVM) but are getting tired of the language itself, I'd recommend trying out Scala or Groovy. It's a bit like Java with a more modern syntax (or Jython if you're feeling a twinge of python-envy).

share|improve this answer
add comment

Learning a bit about functional programming can improve the way you write object oriented software. For example the value of immutable objects, lack of side effects and new ways of seeing and appreciating abstractions - favoring 'verbs' over 'nouns'. But as others noted, java is no functional language and you may make the lives of other programmers reading your code hard when using unexpected paradigms.

Have a look at what the authors of google guava have to say about the functional idioms built into their library.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.