Thursday, July 22, 2010

Java now has Objects

As far as I'm concerned, Java has always been a "Nearly Object Oriented" language. When translating a model into real code you end up specifying the properties of the object and the methods with the business logic and translating that into fields, methods with the business logic, and methods to make it possible to relate fields like properties.

Eclipse makes much of this easier with various code generation plug-ins and features yet, despite that, I have wasted hours writing, correcting, and and maintaining infrastructure methods such as equals(), getters/setters, hashValue(), toString() .

All that has shifted with the addition of Lombok.

http://projectlombok.org/

Project Lombok uses Java 5 annotations in combination with byte code generation to allow compile time generation of all of the infrastructure methods to have fields become properties.

For example:

You can use the @Data annotation on a class to automatically generate the toString, hashCode, equals, and getters for all fields and setters for all nonfinal fields. It will also generate a free constructor to initialize your final fields.

Voila ! Instant domain object.

If you want you can break these things down in a more à la carte manner by using annotations such as:

@Getter / @Setter
@ToString
@EqualsAndHashCode

It also has some annotations I have not yet played with or evaluated:

@Cleanup - Automatic resource management: Call your close() methods safely with no hassle.
@Synchronized - synchronized done right: Don't expose your locks.
@SneakyThrows - To boldly throw checked exceptions where no one has thrown them before!


To use it on an Ant based compile you simply include it in your class path. To use an eclipse you need to run the installer and point it at the eclipse installation in question. It will modify the eclipse.ini file so that the runtime compile of Eclipse will automatically process the annotations.

To sum up:

PROS:

  • Radically simplifies my life when dealing with business domain objects
  • Byte code generation is nicely hidden and transparent.
  • Simple to use for command line builds.

CONS:

  • Eclipse install requires additional work and documentation if you are documenting your build environment for someone else.

UNKNOWNS:

  • How well it plays with tools like AspectJ.