Java
Lombok
Coding
Getter/Setter Methods
Software Development

Omitting one Setter/Getter in Lombok

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Project Lombok is a popular Java library used to minimize boilerplate code such as getters and setters, constructors, equals(), hashCode(), and toString() methods among others with simple annotations. This library automatically plugs into your editor and build tools, and enhances your Java code by inserting the necessary code during compilation. A common practice among developers using Lombok is to include annotations like @Data, @Getter, or @Setter at the class level to automatically generate these methods for all fields. However, there are instances when a developer might want to omit a setter or getter for a specific field to encapsulate the field's visibility from other parts of the application.

Why Omit a Setter or Getter?

The decision to omit a setter or getter usually revolves around the concept of immutability and encapsulation in object-oriented design:

  • Immutability: By not providing a setter, you ensure that the value once set cannot be altered, which is a critical aspect of creating immutable objects.
  • Encapsulation: Omitting getters and/or setters can restrict the visibility of the inner workings of the class, thus hiding its internal data and ensuring that objects cannot put the data of your class into an invalid state.

Using Lombok to Omit Setters or Getters

To omit a setter or getter in a Lombok-annotated class, you can use the @Getter and @Setter annotations directly on the fields for which you want to generate or suppress these methods. By default, if you annotate the whole class with @Getter or @Setter, all fields will have getters and setters. If you need to exclude a particular field, you must explicitly define the behavior for each field.

Example:

Suppose we have a class UserProfile, and we want to make the userId field immutable and the userType field not readable from outside the class:

java
1import lombok.Getter;
2import lombok.Setter;
3
4public class UserProfile {
5    @Getter
6    private final Long userId;
7    private String username;
8    @Setter
9    private String email;
10    private String userType;
11
12    public UserProfile(Long userId) {
13        this.userId = userId;
14    }
15
16    // Standard getters and setters for only `username` and `email`
17    public String getUsername() {
18        return this.username;
19    }
20
21    public void setUsername(String username) {
22        this.username = username;
23    }
24}

In this example:

  • The userId field has a getter but no setter, making it immutable after being set once through the constructor.
  • The userType field neither has a getter nor a setter, thus it is completely encapsulated from external access.

Comparison of Field Accessibility

To summarize, here's a quick look at field accessibility modifications offered by Lombok:

FieldGetterSetterImmutableFully Encapsulated
userId
username
email
userType

Additional Considerations

  • Selective Annotations: Use field-level annotations judiciously to avoid unnecessarily exposing or mutating your class’s fields.
  • Alternative Patterns: For more complex scenarios involving immutable or partially mutable objects, consider using other patterns such as a builder (@Builder) which allows finer control over object construction.
  • Integration with IDEs: Ensure your IDE is configured with a Lombok plugin to recognize and correctly process Lombok annotations.

Conclusion

Through selective use of Lombok's @Getter and @Setter annotations at the field level, developers gain finer control over class field access and mutable state. This results in more maintainable and robust Java code, complying with best practices in object-oriented design. The flexibility of enabling or disabling these methods per field facilitates adherence to design principles such as immutability and encapsulation.


Related reading
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.