Get rid of Getters and Setters

Last Updated on by

Post summary: Use Project Lombok to reduce the amount of code you have to write by automating Getters and Setters generation

UPDATE: After having some real usage of project Lombok I would recommend not to use it. There are situations where debugging is not possible, also code navigation through IDE is hard.

C# has Properties, special methods which look like public data members but behind the scenes are special methods. This allows data to be accessed easily and less code to be written.

Inconvenience

Properties behavior in Java is implemented with so-called Getters and Setters which generally are normal methods with a special name. Encapsulation is important OOP principle that requires data fields to be hidden from outside world. Even in test code, it is not good to break this principle. So we need to write lots of Getters and Setters to expose data fields. Even that all IDEs provide a way to generate them automatically worst thing is that class is polluted with lots of methods that are actually insignificant.

Get rid of Getters and Setters

Project Lombok is a solution for having less code in your classes. You do not need to worry about writing Getters and Setters anymore. They are automatically added at compile time. What you need to do is just annotate your class or fields. One option is to directly put a @Data annotation on class level. Another option is to put restrictions on each field if you are too picky.

Code

In some cases, there is some processing of values Getter or Setter. This is not a problem you can implement only this method. If Lombok sees there is Getter or Setter it is ignoring it at compile time. In the example, below correct getIsbn() is being used.

import lombok.Data;

@Data
public class Book {
	private String isbn;
	private String name;
	private String author;

	public Book(String isbn, String name, String author) {
		this.isbn = isbn;
		this.name = name;
		this.author = author;
	}

	public String getIsbn() {
		return "ISBN: " + isbn;
	}
}

Conclusion

Although getters and setters are generated only once the code is more readable without them.

Category: Java