ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

Introduction to Lombok Part One

Updated on August 15, 2019
JoeFullerWriting profile image

Joe has extensive experience in software engineering, particularly in the Java programming language and AWS technologies.

Boilerplate Code is Painful

It's one of the biggest complaints developers have about Java, "There is too much boilerplate." To be honest I really like Java, but I have to admit that there is a lot of boilerplate code that you have to constantly repeat such as:

  • Constructors
  • Getters
  • Setters
  • Builders
  • Null checking

Thankfully modern IDEs such as IntelliJ and Eclipse can auto-generate a lot of this code for you using a few swift keyboard shortcuts. However there is still a problem; you have to see all that code. The boilerplate still exists, you didn't have to write it but you still need to see it and waste precious brainpower being distracted by it as you search for the real functionality.

This is particularly egregious in classes that are used for simple data storage commonly called POJOs (Plain Old Java Objects) whereby all you really care about is the instance variables but you need to see many lines of boilerplate as well.

Consider the simple data class below:

We only really care about the private instance variables but to make this class useful we need a lot of boilerplate.
We only really care about the private instance variables but to make this class useful we need a lot of boilerplate.

That's a lot of boilerplate for such a simple POJO, now imagine you have hundreds of POJOs and all of a sudden your project is full of boilerplate code that you need to see in code reviews and sift through to find the actual functionality of the class. But what if I told you using Lombok all that boilerplate could be reduced to what is in the class below, well it is possible and this article is going to introduce some of Lomboks most useful features that will save you time and code review effort.

Using Lombok all that boilerplate can be reduced to 3 annotations on the class declaration.
Using Lombok all that boilerplate can be reduced to 3 annotations on the class declaration.

@AllArgsConstructor

As you seen in the example above @AllArgsConstructor does exactly what you would expect it to, it creates a single contructor featuring arguments for all the instance variables in the class. Later we will see how you can create constructors with a more restricted set of the instance variables using @RequiredArgsConstructor.

So let's see an all arguments constructor before using Lombok:

A big clunky all arguments constructor... ugly!
A big clunky all arguments constructor... ugly!

Now have a look at code with identical functionality except we used @AllArgsConstrcutor:

Much cleaner, all the same functionality in one annotation.
Much cleaner, all the same functionality in one annotation.

@Getter / @Setter

These two are very easy to explain and really require no demonstration (they were already covered in the introductory example):

  • @Getter: Using this generates getter methods for each instance variable in your class. So if you have 1 instance variable called name then @Getter will generate the getName() method for you. Alternatively you can place @Getter on individual instance variables if you don't want to generate a getter for all your instance variables.
  • @Setter: Using this generates setter methods for each instance variable in your class. So with the previous examples 1 instance variable called name then @Setter will generate the setName(String name) method for you. Alternatively you can place @Setter on individual instance variables if you don't want to generate a setter for all your instance variables.

@NoArgsConstructor

This is to be used in conjunction with @AllArgsConstrcuctor and/or @RequiredArgsConstructor. Once you add a non-default constructor the default empty constructor is no longer available unless explicitly made so. That's exactly what @NoArgsConstructor is for, it generates a default empty constructor for you. Take a look at the before and after images below.

A class with both a full constructor and an empty (default) constructor.
A class with both a full constructor and an empty (default) constructor.
The same class using two Lombok annotations, it is much cleaner.
The same class using two Lombok annotations, it is much cleaner.

@NonNull

This is by far my favourite Lombok annotation as it helps deal with one of every developers pet peeves, the dreaded NullPointerException.

Specifically @NonNull can be used in two instances:

Parameters

When used to annotate parameters @NonNull will automatically generate a check for null in the method before any other code, giving you a nice way of ensuring a null value doesn't get caught deep in your methods logic. It also serves a documentation purpose, as a developer if I inspect someone else's method and see parameters annotated with @NonNull I know to check I will not pass null to that method. This documentation benefit helps avoid other developers using your methods in ways you didn't initially intend.

The two methods below are functionally equivalent, though the second using @NonNull is much cleaner.

These two methods are equivalent, but one is much cleaner.
These two methods are equivalent, but one is much cleaner.

Instance variables:

Marking instance variables with @NonNull does exactly what you might expect, it generates null checks anywhere the variable is being set. For example in constructors that feature the variable @NonNull will create a null check. An example is given below of two equivalent classes, one using @AllArgsConstructor with @NonNull and another using vanilla Java.

These two Coordinate classes are functionally identical. Lombok has removed all the boilerplate in the second implementation.
These two Coordinate classes are functionally identical. Lombok has removed all the boilerplate in the second implementation.

@RequiredArgsConstructor

This is similar to @AllArgsConstructor with one distinct difference; only final instance variables and those marked with @NonNull will be included in the generated constructor. Those instance variables marked with @NonNull will also have the null check generated as we seen previously in the @AllArgsConstructor example.

Please see the example below to see what instance variables get included in the generated @RequiredArgsConstructor and which don't.

Both implementations act the same.
Both implementations act the same.

@Builder

The builder pattern is a very common design pattern in Java for classes that contain a lot of instance variables, however when implemented in a non-Lombok way it is ugly, you need a static inner class and anytime you add a new instance variable the builder class also needs updated. This leads to literally hundreds of lines for a very repetitive implementation.

The @Builder annotation from Lombok reduces all those lines into one single annotation, allowing you to stop worrying about maintaining your manually coded builders and get on with the important programming tasks! To see the impact of the @Builder annotation all you need to do is look at the example below.

The builder pattern is where Lombok really shines in reducing boilerplate code. It's hard to believe these two classes are equivalent!
The builder pattern is where Lombok really shines in reducing boilerplate code. It's hard to believe these two classes are equivalent!

@ToString

Whether you're stuck debugging a program using system print calls or need to log important details of objects you are processing we have all needed to use a well implemented toString() method.

I have even seen some developers serializing objects to JSON strings in order to log them so all the variables and their values are listed. This is an expensive operation generally requiring external libraries like GSON or Jackson.

We can achieve the same outcome with a single Lombok annotation; @ToString. This annotation can be configured to exclude certain member variables by annotating them with @ToString.Exclude. You can make it call the toString() method of it's superclass as well using @ToString(callSuper=true) and you can make it include all the field names using @ToString(includeFieldNames=true).

I won't add an example of this annotation to this article because it doesn't fit nicely into images due to the line length of the equivalent toString() method when implemented in vanilla Java. However you can follow this link to the official Lombok @ToString documentation.

End of Part One

So we have covered some of Lomboks best boilerplate reducing annotations, in part two we will dive in to some more boilerplate reduction using:

  • @Value
  • @Data
  • @EqualsAndHashCode

However we will also dive into some more advanced Lombok features such as:

  • @Synchronized
  • @Cleanup

I look forward to seeing you in part two and hope this has served as a good introduction to how to reduce boilerplate Java code using Lombok annotations.

Comments

    0 of 8192 characters used
    Post Comment

    No comments yet.

    working

    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, hubpages.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://hubpages.com/privacy-policy#gdpr

    Show Details
    Necessary
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
    Features
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Marketing
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Statistics
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)
    ClickscoThis is a data management platform studying reader behavior (Privacy Policy)