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.
     
    final Foo bar = new Foo();
    

    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:
     
    List<Person> beerDrinkers = new ArrayList<Person>();
    for (Person p: persons) {
        if (p.getAge() > 16) {
            beerDrinkers.add(p);
        }
    }
    

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

     
    Predicate<HasAge> canDrinkBeer = new Predicate<HasAge>() {
        public boolean apply(HasAge hasAge) {
            return hasAge.getAge() > 16;
        }
    };
    
    List<Person> beerDrinkers = filter(persons, canDrinkBeer);
    

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

    Predicate canDrinkBeer = new Predicate() {
         public boolean apply(HasAge hasAge) {
             return hasAge.isOlderThan( 16 );
        }
    };
    

    which would lead to better code down the road:

    Predicate canDrinkBeer = new Predicate() {
        public boolean apply( HasAge hasAge, HasAge otherAge ) {
            return hasAge.isOlderThan( otherAge );
        }
    }
    

    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,

     
    List beerDrinkers = filter(filter(persons, canDrinkBeer), isMale);
    

    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
     
    public int add(int a, int b) 
    {
      int result = a + b;
      return result;
    }
    

    write

     
    public int add(int a, int b) { return a + b; }
    

    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.
     
    public class Person implements Nameable, Hireable, LivesAt {
       ...
    }
    
    public interface Nameable {
      String getName();
    }
    

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

     
    public void print(Nameable name) {
      System.out.println(name.getName());
    }
    

    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:
     ConcurrentMap graphs = new MapMaker()
           .concurrencyLevel(32)
           .softKeys()
           .weakValues()
           .expiration(30, TimeUnit.MINUTES)
           .makeComputingMap(
               new Function() {
                 public Graph apply(Key key) {
                   return createExpensiveGraph(key);
                 }
               });
  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

     
    public class Point {
       private int x;
       private int y;
    
       pulic Point(int x, int y) {
          this.x = x;
          this.y = y;
       }
       public int setX(int newX) {
          x = newX;
       }
       public int getX() {
         return x;
       }
       ...
    }
    ...
    int x = p.getX();
    int y= p.getY();
    

    write

     
    public class Point {
       public final int x;
       public final int y;
    
       pulic Point(int x, int y) {
          this.x = x;
          this.y = y;
       }
    }
    ...
    int x = p.x;
    int y = p.y;
    

    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.

   Page page = page(
      html(
        body(
          // A comment
          h1("Name games"),
          p("Hello ${coolName}, and hello", "id:${id}"),
          ul(
            new Loop("stefanie", "${name}") {
              protected Element each(String item) {
                return li(item);
              }
            }),
          loop("[${number}] ", "number", 1, 2, 3),
          text("..."),
          box("Warning private!"),
          p("Are you dynamic?"),
          // Some dynamic content
          new Action() {
            protected String with(Context context) {
              return "I'm dynamic, " + context.get("name") + ".";
            }
          }
        )
      )
    );

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.

  public static Element body(String body) {
    return new Element("body", body);
  }
  public static Element body(Element... elements) {
    return new Element("body", elements);
  }
  ...

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

h1(
   p("One"),
   p("Two"),
   p("Three")
);

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

  "Hello " + name + "!"

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

  "Hello ${name}!"

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

   p("Hello ${coolName}, and hello", "id:${id}, class:list"),

Loop and Action classes allow for dynamic content.

          
          ul(
            new Loop("stefanie", "${name}") {
              protected Element each(String item) {
                return li(item);
              }
           }),

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

public static Element box(String text) {
  return div(
                 p(text)
           );
}

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.

Graeme – the Grails bug buster

While testing Reposita with the Grails repository, I was amazed about Graeme who is the Grails project lead and recently became the CTO of G2One.

Scanning the Grails subversion commits and searching for bug fixes, Graeme seems to be a very very active bug buster. One in four commits is a bug fix. Perhaps this directly contributes to the Grails success story. I hope he keeps up fixing bugs, now that he's CTO.

See for yourself:

Graeme and Bugs