DEV Community

Building Generic Payloads with the Builder Pattern in Java

Partha Sutradhar on October 30, 2023

Java Generics can be used to create reusable code for structured responses in web services. This makes the code easier to maintain and scale. Gener...
Collapse
 
siy profile image
Sergiy Yevtushenko

Builder pattern can be used only to optional parameters. Otherwise, it may result in uninitialized values and NPE.

Collapse
 
parthasutradhar profile image
Partha Sutradhar

Thanks Sergiy. Yes, it'll result in NPE without optional params. Let me know if we can do something to fix this?

Collapse
 
siy profile image
Sergiy Yevtushenko

There is a Fluent Builder pattern, suitable for cases when all (or majority) of parameters are required. You may find interesting this article.

Thread Thread
 
parthasutradhar profile image
Partha Sutradhar • Edited

Yes, Step Builder will force client to provide datum.

Thread Thread
 
siy profile image
Sergiy Yevtushenko

Moreover, this pattern enforces order in which fields are assigned. This is helpful in many situations, especially when changes in code are compared.

Collapse
 
masum profile image
Abdullah Al Masum

Awesome content. We may now implement this pattern similarly in Asp.Net Core. Hope this architecture-related article continues.

Collapse
 
parthasutradhar profile image
Partha Sutradhar

Thanks Masum. I'll try to update on this type of article.

Collapse
 
anupamakib profile image
Mir Anupam Hossain Akib

Nicely explained. It will help me to learn Builder Patterns. Thanks for the article.

Collapse
 
parthasutradhar profile image
Partha Sutradhar

Thanks, Anupam for your feedback. I'll update regularly on this.

Collapse
 
khair_al_anam profile image
Khair Alanam

This is such an informative article on Builder Patterns! The code snippets shown are pretty good :D and really explains the use of Payload with Builder Pattern.

Collapse
 
parthasutradhar profile image
Partha Sutradhar

Thanks, Alanam. I'll try to update regularly on Java Design Pattern's and on Software Architecture.

Collapse
 
pathus90 profile image
Diallo Mamadou Pathé

Nice article.
Lombok has an annotation @builder.

Might be usefull And can reduce boilerplate code

Collapse
 
parthasutradhar profile image
Partha Sutradhar

Thanks Pathe. Will try using this from now on.