I hate boiler-plate code, there I said it. It is not that I am too lazy to write code mindlessly- scratch that. It’s not just that I am too lazy to write boiler plate code, boiler-plate code obfuscates the intent of the developer, it puts more lines of code that a reader has to go through to figure out what is actually going on and the more code you write the more-likely you are to introduce bugs. Having said that, boiler code is a necessary evil, right? Wrong. With Lombok we get the benefits of boiler-plate code without having to deal wit it. It’s nicely hidden away behind annotations.
Before we start looking at Lombok code a word about eclipse code generation. While eclipse has a handy feature to generate a lot of boiler plate code for you which means there will be no bugs introduced and you don’t have to write code yourself. However the eclipse generated code is still in your source hence any one reading the code still has to sift through some crud before finding the intent of the programmer. As we will see in Lombok we can reduce the visible code to only that which shows programmer intent. To whet your appetite and show the power of Lombok and annotations in general here is an actual source file from a rest service I am currently working on.
Notice the utter lack of any methods, not constructors, getters or setters. However, I have access to a whole slew of boiler-plate code as you can see from the eclipse outline view below.
Below is exactly the same class now with all the boiler-plate code generated by eclipse. we go from about 20 lines of code to about 150. Which would you like to read and debug? Take another look at the long form code, notice anything funny? Look at the getter for gameId, I lied its not exactly the same class I added the toLowerCase method. This highlights the problem with boiler place code even if it is auto-generated. It could be that the toLowerCase is desired behaviour in this case. However, as some one reading the code you have an understandable predisposition to assume the getter for Game ID was just a plain old getter. However, unless you read every single getter you would not know that this one was different. With lombok the only explicitly defined getter (or any other method) will be the one that differs from the expectation. Hence you would not need to read any code just to confirm it is doing what you already assumed it would. Instead you would only see code that differentiates this getter from any other.
I will not go over all the features and annotations available in Lombok, the project page does a very good job. However, I do want to highlight how easy it is to integrate Lombok with your project. Just include the Lombok Jar in your class path. If you use maven use the dependency shown below. If you use eclipse lombok jar file and restart eclipse so that you can get code assists for the generated code.