Go Ahead: Next Generation Java Programming Style

Many companies and developers move away from Java to new languages: Ruby, Python, Groovy, Erlang, Scala. You might be trapped with Java.

Even if you've trapped, you can change your programming style and reap some of the benefits of those new languages. In the last 15 years Java programming style has changed significantly:

  1. Final is your new love: More and more Java developers in the teams I've worked with, started to use final. Making variables final prevents changing those values. Most often, if you reasign a value, it's a bug or you should use a new variable. Final prevents bugs and makes code easier to read and understand. Make everything immutable.

    I've written more about this topic in "All variables in Java must be final".

  2. No setters. Many Java developers automatically - sometimes with the evil help of an IDE - write setters for all fields in their classes. You should not use setters. Think about each setter you want to write, are they really necessary for your fields? Better create new copies of your objects if values change. And try to write code without getters either. Tell, don't ask tells you more about the concept.
  3. Do not use loops for list operations. Learning from functional languages, looping isn't the best way to work on collections. Suppose we want to filter a list of persons to those who can drink beer. The loop versions looks like:

    This can - even in Java - be rewritten to a more a functional programming style. For example using Google collections filter:

    As remarked by Dave Jarvis, I should have dropped the getter, and he's right ;-)

    which would lead to better code down the road:

    The predicate version is slightly larger, but consists of two parts. Each one is easier to understand. While the loop version gets unreadable fast with new requirements, the functional version can easily be combined,

    More on this at the Metaphysical Developer.

  4. Use one liners: Write concise code. Java is a noisy language. But don't make it noiser as it needs to be. Instead of


    IDEA and possibly other IDEs can keep oneliners formatted as oneliners, if you tell them so.

  5. Use many, many objects with many interfaces. Domain driven design currently makes a big splash. A class should be splitted into many roles, implementing many interfaces. This way the class is reusable.

    Methods should be written to only work on roles, not classes. This way methods can work on more objects. Another benefit is lower coupling.

    I've written more about that in "Never, never, never use String in Java ".

  6. Use Erlang-Style Concurrency. The Java concurrency primitives like locks and synchronized have been proven to be too low level and often to hard to use. There are better ways to write concurrent code. Erlang Style concurrency is one of them - in Java there are many ways to achive this in Java - I've written about them here. Newer ones are Akka and Actorom. You can also use Join/Fork or the myriad of data structures in java.util.concurrent.
  7. Use Fluent Interfaces. Fluent interfaces can make your code much more readable and shorter. A very good example is the MapMaker API in Google Collections:

  8. Data Transfer Objects without setters and getters. If you have simple data holders or data transfer objects, don't write boiler plate code with getters and setters. I know this is heresy in Java, but just use public fields. Instead of


    Refactoring is easy, should you need it. If you do not control all the code and it's usage, you might need to be more careful though.

This tips lead to better Java code. Try them in your next Java class. What do you think? I'd like to hear how your Java coding style has changed in the last 10 years.

Uodate: Some thoughts to Cedrics thoughts.

As the author of the post, your thoughts are appreciated, some of mine:

"Besides, it's convenient to be able to mutate object if you want to use pools."

No setters doesn't mean you can't mutate objects, it's just that plain setters are not object oriented thinking. How about stop() vs. setStop(true);

"I think the first example is more readable than the second one that uses Predicates."

I think your assumptions are wrong. Loops are procedural code, while Predicates are, encapsulated, reusable, understandable objects. Nothing to do with functional programming, plain OO - it's only ursurped by functional programming, therefor I refer to it as FP.

No future for functional programming in 2008 – Scala, F# and Nu

On Lambda the ultimte there is a recent post with a language prediction for 2008, which mainly predicts the rise of functional programming and the rise of Scala in particular: "My prediction is a little bit more conservative, but I predict Scala will gain momentum, and at least one high visibility project will use Scala". Brandon chimes in with "The most important thing to emerge from the discussion is the larger role functional programming will play. It seems like a safe bet." A safe bet, really? I more sceptical, as written in my post about Qi4j and Scala.

The blogosphere is full of functional programming language advocates and the coming rise of functional programming in application development. But has anything changed since Lisp was invented in 1958? Functional programming languages have existed for more than 50 years now, and didn't make any inroads into application development. What happend to the acclaimed golden age of functional programing, about which Peter Christensen writes? Will it come back? I dispute in a comment to that post that there ever was a golden age of functional programming, it was a fringe language from the beginning. There was a golden age of Fortran.

John McCarthy - no not THAT McCarthy - invented Lisp back in 1958. From there functional programming gained much appeal to programmers because of it's clean and consistent style. Everything in Lisp is a list. Even the program itself. Because good programmers have a feel for aesthetics in programming style, they have a warm feeling for Lisp. Functional programming is also a powerful tool for software development. And developers like power. As Paul Graham writes in "Revenge of the Nerds" about power in languages with the aim to praise Lisp:

As an illustration of what I mean about the relative power of programming languages, consider the following problem. We want to write a function that generates accumulators-- a function that takes a number n, and returns a function that takes another number i and returns n incremented by i.

He cites an example in Lisp, that implements an accumulator in a nice and pure way:

Functional languages excel at mathematical and list processing problems. Most problems to solve in the enterprise are of a different type though. When moving to real problems then, functional programming languages get ugly as an ugly duck. With no swan in sight. Looking at examples from Implementing a blog in Common Lisp: Part 1, we see how ugly it can get. In Java land people a frustrated about XML, but see the brace chaos in Lisp, just to open a database:

And defining a blog domain object doesn't look very readable either:

compared to a Groovy example:

or a Java one in Qi4j:

Another example from nu, the rising functional star for Macos X. This time with the famous Currency converter example which creates a window:

With an equivalent example in Groovy to build a Swing UI:

Mostly equivalent with the Groovy example which is still slightly easier to read and understand, even by someone who doesn't know Groovy. Mainly because Groovy is more expressive and not everything has to be pressed into a list (though the nu example contains more than lists as nu aims for object orientation).

In a discussion about Arc, a functional language, stevecooperorg writes about Lisp and the use of Emacs/Slime:

I'd like to write the next Viaweb, and I'd like to write it in Lisp. But if the basic language is inviting, the rest of the environment is sorta hostile; a shangri-la in a swamp.

That's another problem of most fringe languages. People - the enterprise? - need to know too much beside the language. Using a fringe editor which most people abandoned in the 80s and "a decent knowledge of system administration" is too high a barrier.

Power is a good thing it seems. From my experience most developers can't handle power. They misuse it. If your development team is less than 5 developers the chance is high that all of them are alpha developers. And your interviewing process was rigorous of course. Above ten and the chances are high that there won't be only alpha coders. Power is a dangerous feature of a language then.

Do powerful languages scale? Do dynamical type reference languages, which most functional languages are, scale? Scaling in time and organisation? Does it scale from 6 months to 10 years and does it scale from 2 people to 50? I have my doubts for years and still ask anyone to show me how those languages scale. I really want to know. Others too. Manageability writes about Python and Chandler:

What I find interesting is that Chandler started as a Python project with bold claims such as "Python programs are both concise and readable, this makes it excellent for rapid development by a distributed team" and "Chandler design goals: ... design a platform that supports an extensible modular architecture". I was hoping to see this project as a testament to Python's viability to large scale development.

The jury is still out, but I wouldn't bet on scalability. As a project manager during the 90s two of my projects didn't scale and had to be rewritten, one in Python and one in Perl. But it could just be me.

What happend to Haskell and Erlang, the functional hypes of 2006 and 2007? The Blogosphere has mainly lost interest in those lately. Scala and F# seem to be en vogue in our days. Arc perhaps is next in line to be en vogue. Certainly after Scala, which is next the next thing after Java as Bruce Eckel claims. What has changed from the days of Lisp 50 years ago I asked. Scala and F# are different from Haskell, Erlang - and Lisp. They build on an a proven plattform, on libraries that people know. Scala mostly on the JDK and Java ecosphere, F# on the Microsoft universe and .NET. They both are the most promising functional candidates when it gets to momentum. The transit for C# and Java developers seems to be easiest compared to other languages. Will that be enough for them breaking through into the mainstream?

Will the release of Arc, written as a pet project by Paul Graham the greatest functional rock star, help with functional programming? No, certainly not. Arc lost it's appeal even before it was released. While waiting for the Arc blessing, people moved on to Scala, Erlang or F#.

Don't kid yourself. There will be no rise for application and especially enterprise development in functional programming (See what happens when you use a Perl script to do your billing, not that I haven't screwed up in the past with Java ;-) Which doesn't mean to stop using functional programming languages. It's fun, keep going.

Thanks for listening.