The Open Even App Android project contains data/model classes like Event, Track, Session, Speaker etc which are used to fetch data from the server and store data in the database. Each model contains private fields, getters, setters and toString() method which are used to change data of the object, access data of the object, logging and debugging. Adding all these methods manually makes the code boilerplate.
In this blog post I explain how to use Lombok to reduce boilerplate code in the model class.
To set up Lombok for your application you have to add the dependency in your app module’s build.gradle file.
Install Lombok plugin
In addition to setting up your gradle project correctly, you need to add the Lombok IntelliJ plugin to add Lombok support to Android Studio
- Go to File > Settings > Plugins
- Click on Browse repositories
- Search for Lombok Plugin
- Click on Install plugin
- Restart Android Studio
Write model class
Lombok has annotations to generate Getters, Setters, Constructors, toString(), Equal() and hashCode() methods.
@Getter, @Setter, @ToString, @EqualsAndHashCode
@Data is a shortcut annotation that bundles the features of @Getter, @Setter, @ToString and @EqualsAndHashCode
Here I am only defining track model because of its simplicity and less complexity.
Create and use object
After defining models you can create an instance of the object and you will notice that you can access all the getters and setters.
You can also specify which fields to include and exclude in the toString(), equals() and hashCode() methods using @ToString, @EqualsAndHashCode annotation.
Lombok has three methods to generator constructors
- @NoArgsConstructor: It generates constructor with no parameters
- @RequiredArgsConstructor: It generates a constructor with 1 parameter for each field that requires special handling.
- @AllArgsConstructor: It generates a constructor with 1 parameter for each field in your class.
As you can see, Lombok uses succinct annotations to generate methods such as getters, setters, and constructors. It can easily help you get rid of hundreds of lines of boilerplate code. Lombok also allows you to make your code more expressive, concise and can help you avoid some bugs. To learn more about Lombok project follow the links given below.