DEV Community

Reza Akhgari
Reza Akhgari

Posted on

How Fluent Interface Design Pattern extends capability of Java record

In this short post, I do not intend to make a comparison between using the record in Java 17 and Lombok, but since nowadays the use of record is controversial, I think it is good to have a look at how to use it with builder pattern although inherently lacks this feature.

Suppose we are going to define an address using record. Depending on the number of required fields, your record will have a sequence of parameters in its constructor. So using new do you instantiate your address with large number of parameters and face with the code bloating or do you have another thought to increase the code readability?

In the absence of Lombok, it is internally possible to reinforce constructing capability of the record adding a real Fluent Builder pattern.

First, it is supposed to define some interfaces:

public interface Country<T> 
    T country(String T);
}

public interface City<T> 
    T city(String T);
}

public interface Street<T> {
    T street(String T);
}

public interface Building<T> {
    T building(String T);
}

public interface Flat<T> {
    T flat(String T);
}

public interface PostalCode<T> {
    T postalCode (String T);
}

public interface Build<T> {
    T build();
}
Enter fullscreen mode Exit fullscreen mode

Then we implement our customized record:

public record Address(String country, String city, String street , String building , String flat, String postalCode)
{
    public static Country<City<Street<Building<Flat<PostalCode<Build<Address>>>>>>>

    builder() {
        return (country) ->
               (city) ->
               (street) ->
               (building) ->
               (flat) ->
               (postalCode) ->
               () -> new Address(country,city,street,building,flat,postalCode);
    }
}
Enter fullscreen mode Exit fullscreen mode

Great! Just assign values to our implementation:

Address.builder()
    .country(“Russia”)
    .city(“St.Petersburg”)
    .street(“Kolomenskaya")
    .building(“12a”)
    .flat(“234”)
    .postalCode(“200567”).
    build();
Enter fullscreen mode Exit fullscreen mode

Recap

Even if using Java 17 new language features, many developers still prefer to use class instead of record as this asset inherently lacks using builder now. However, I think it perhaps a good idea to implement constructor for record called by the builder. In this short post I attempted to show how it is possible to use this ability!

Top comments (0)