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

    write

    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

    write

    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.

The best Markup Builder I could build in Java

Using Groovy MarkupBuilders spoiled me for other ways to create HTML pages from code. Others think the same. But in some organizations you have to use Java and can’t use Groovy – at least when you can’t sneak it in.

So I tinkered around in Java to see what’s the best MarkupBuilder I can write with Java. Using DSLs and Fluent Interfaces (times(5).loop), I came up with a nice solution. It’s not Groovy, but it works.

There are some tricks to make it better than most such Markup Builders in Java. I tried to use ideas from building DSLs in Java. Those are using static imports and varargs. The body, html and other elements are static imports from a MarkupBuilder class.

The varargs helps with adding a variable number of childs to an element:

Another problem is how to put object values into the generated markup. String concatenation leads to noisy code

so I decided to use a expression language where the Java unified expression language comes to mind. There is an open source version available called JUEL. Now I can use

Attributes are also treated as expressions and seperated by commas, their names and values seperated with a colon.

Loop and Action classes allow for dynamic content.

I’ve used the template design pattern for this, again with expressions, in a way Spring provides JDBC templates. Another nice idea is with static methods it’s also easy to develop custom, semantic tags, so the developer doesn’t need to know or see the actual HTML markup which is created. For example I used a box “tag” which translates to

Closures in Java 7 will make it much easier to write a MarkupBuilder. The Action and Loop inner classes will go away and the code will be more Groovy like. When they add syntactic sugar to create maps I can drop the “name:value, name:${value}” style for attributes and move to [ "name" : value, "name": value ] instead, which doesn’t need the EL to work. With some small things to add the MarkupBuilder can be used for JSON or XML.

I’m interested and open to all techniques and ideas to improve the markup builder.

Thanks for listening.