Quickly create versatile POJOs

As a programmer, everyone wants to write the code quickly and without creating too many bugs.

First Run: 

When you store complex data you should aim to store it in a POJO (https://en.wikipedia.org/wiki/Plain_Old_Java_Object).  These objects should not have anything other than fields, and basic access to them.

When you have these objects, you sometimes need to write equals, hash, toString methods...
These tasks are very repetitive and can get boring.  Luckily with IDEs either eclipse or IntelliJ you can get the stuff auto-generated.  And you will save some time.  

Maintainability:

Not bad for a start.  But what happens when you decide you need to add a new field to your object?
You have to re-generate equals, hash, toString.  Delete some code, and regenerate.
Not too hard, but error prone, there is a chance you will forget to do it.

There is a quick and elegant way to solve this: use Lombok's annotations. https://projectlombok.org/.
Simply adding @Data all the required fields will be generated at compile time. But with the IDE it is seamless.    https://projectlombok.org/features/Data.html

There are quite a few other useful features @Setter, @Getter, and @Slf4j which will allow you to create a logger quickly.


Real world example: 
Recently I made an update to a POJO (which did not use Lombok annotations) which had an Enum value in it.  I decided I wanted to change said enum value to String so it can accept more values.  I made the change pretty quickly, and the getter and the setter were changed by the IDE automatically.  I had to make a few changes to the methods that were calling the setters, but other than that I thought I was good to go.  The change went to a Peer Code Review and was accepted.

A few weeks later, I noticed that I forgot to change the equals methods.  So the equals method was comparing strings with an "==" which works perfect for primitive values and Enums but does not work at all for String.

If I had used the @EqualsAndHash annotation this would not have been a problem.


Integration: 

Lombok's website is unorganized so the be best way to see what is supported is here: https://projectlombok.org/features/


Lombok can be easily integrated with IDEs: details can be found here: https://projectlombok.org/download.html


More details:
- Eclipse is free and can be downloaded here: https://eclipse.org/downloads/
- For IntelliJ you need a license, 2 week free trial. https://www.jetbrains.com/idea/


Comments

Post a Comment