Java has a bad side that everybody hates π, what is it?
A lot of boilerplate code is the same for most of the applications we write.
Like what? π§
- Getters
- Setters
- Constructors
- Builder pattern
- and many more...
Wouldn't it be nice if someone took care of that work for us?
That is where Lombok introduces itself.
What does it do? π
It generates the byte code for those common tasks (Getters, Setters, etc..) and puts them in our .class files which make them usable by the code we write.
How? π§
We need to add the Lombok dependency to our Maven build.
Then, we just need to annotate the wanted classes, fields with some Lombok annotations.
Let's look at some code! π©π»βπ»
No Lombok π§
public class Human {
private int id;
private String name;
private int ageInYears;
public Human() { }
public Human(int id, String name, int ageInYears) {
this.id = id;
this.name = name;
this.ageInYears = ageInYears;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public int getAgeInYears() {
return ageInYears;
}
public void setName(String name) {
this.name = name;
}
public void setAgeInYears(int ageInYears) {
this.ageInYears = ageInYears;
}
// Builder pattern
public Human id(int id){
this.id = id;
return this;
}
public Human name(String name){
this.name = name;
return this;
}
public Human ageInYears(int ageInYears){
this.ageInYears = ageInYears;
return this;
}
@Override
public String toString(){
return String.format("Human(id=%s, name=%s, ageInYears=%s)",
this.id, this.name, this.ageInYears);
}
}
Lombok π€΄
import lombok.*;
@Getter @Setter
@AllArgsConstructor @NoArgsConstructor
@Builder @ToString
public class Human {
@Setter(AccessLevel.NONE)
private int id;
private String name;
private int ageInYears;
}
The Maven dependency looks like this
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.16</version>
<scope>provided</scope>
</dependency>
Note: the version part will change depending on the last release of Lombok.
What just happened? π΅οΈββοΈ π΅οΈ
- we used annotations to generate
- Getters
- Setters
- Constructors
- Builder pattern
- toString implementation
We can also make tweaks on some annotations, like the setter for the id field.
- We set its access level to None, meaning that we don't a setter to be generated for it.
Was it worth it? ππ
We wrote 52 lines when not using Lombok.
We wrote 8 lines when using Lombok.
Lombok helped us shrink our code size by nearly 4 times. Those numbers can go up even more when having more variables in our classes.
Lombok has a lot more annotations that offer a ton of help, to view them all visit their website.
Conclusion ππΎ
Lombok helps us focus on our business code and not worry about the little details of getters/setters/constructors/common design patterns and other Java constructs.