Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Partha Sutradhar
Partha Sutradhar

Posted on • Edited on

     

Building Generic Payloads with the Builder Pattern in Java

Java Generics can be used to create reusable code for structured responses in web services. This makes the code easier to maintain and scale. Generics allows the Payload class to be flexible, reusable, and consistent for backend and client-side developers.

Introduction

A well-structured response from a backend service provides clear information about the outcome of the request, any relevant data, any associated messages, and often metadata such as the timestamp.

Structured responses from backend services

A well-structured response from a backend service:

  • Provides clarity about the outcome (success or failure).
  • Contains any relevant data related to the response.
  • May provide any associated message with the response.
  • Often includes metadata, like the timestamp.

Using Generics to define a response

Consider the Payload class provided. Here's a breakdown of how it's structured:

  • Message: A description of the outcome of the request, such as "Request Successful" or "Item not found."
  • Status: A numerical status code, such as 200 for OK or 404 for NOT FOUND.
  • Payload: The actual data being sent in the response. This can be of any type, thanks to the use of Generics.
  • Timestamp: The time at which the response was created.

In short: The Payload class provides a structured way to represent backend responses, with fields for the message, status, payload, and timestamp.

Using the Builder Pattern

The builder pattern allows us to construct Payload objects in a more expressive way, as shown in the following example:

Payload<String>successPayload=newPayload.Builder<String>().message("Request successful").status(PayloadStatus.SUCCESS).payload("This is the response data").build();
Enter fullscreen modeExit fullscreen mode

Benefits

  • Flexible: Payload can be of any type, thanks to Generics.
  • Reusable: A single Payload class can be used for many different response types.
  • Consistent: All responses have a consistent structure.

Usage

// Create a Payload with a String payload.Payload<String>successPayload=newPayload.Builder<String>().message("Request successful").status(PayloadStatus.SUCCESS).payload("This is the response data").build();// Create a Payload with a User object payload.Useruser=newUser("John","Doe");Payload<User>userPayload=newPayload.Builder<User>().status(PayloadStatus.SUCCESS).message("User found").payload(user).build();// Create a Payload with a List of Items payload.List<Item>items=Arrays.asList(newItem("Book"),newItem("Pen"));Payload<List<Item>>itemsPayload=newPayload.Builder<List<Item>>().status(PayloadStatus.SUCCESS).message("Items fetched").payload(items).build();// Create a Payload with an error message.Payload<Void>errorPayload=newPayload.Builder<Void>().status(PayloadStatus.ERROR).message("Something went wrong!").build();
Enter fullscreen modeExit fullscreen mode

Payload Builder Pattern

The Payload Builder Pattern is a design pattern that allows you to create complex objects in a step-by-step manner. It is especially useful for creating objects with many optional parameters.

@Getter@ToStringpublicclassPayload<T>{privatefinalStringmessage;privatefinalintstatus;privatefinalTpayload;privatefinalDatetimestamp;privatePayload(PayloadStatusstatus,Stringmessage,Tpayload){this.status=status.getCode();this.message=message;this.payload=payload;this.timestamp=Date.from(Instant.now().atZone(ZoneId.of("UTC")).toInstant());}publicstaticclassBuilder<T>{privateStringmessage;privatePayloadStatusstatus;privateTpayload;publicBuilder<T>message(Stringmessage){this.message=message;returnthis;}publicBuilder<T>status(PayloadStatusstatus){this.status=status;returnthis;}publicBuilder<T>payload(Tpayload){this.payload=payload;returnthis;}publicPayload<T>build(){returnnewPayload<>(status,message,payload);}}}
Enter fullscreen modeExit fullscreen mode

Conclusion

The Payload class with builder pattern is a flexible, reusable, and consistent way to represent responses from a backend service. It is easy to use and can be applied to a variety of use cases.

Top comments(13)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss
CollapseExpand
 
siy profile image
Sergiy Yevtushenko
Writing code for 35+ years and still enjoy it...
  • Location
    Krakow, Poland
  • Work
    Senior Software Engineer
  • Joined

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

CollapseExpand
 
parthasutradhar profile image
Partha Sutradhar
I'm a Software Engineer with a strong experience that involves in JVM/CLR based technology and machine learning. Besides programming, I have an immense amount of interest in music.
  • Location
    Dhaka, Bangladesh
  • Pronouns
    He / Him
  • Joined

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

CollapseExpand
 
siy profile image
Sergiy Yevtushenko
Writing code for 35+ years and still enjoy it...
  • Location
    Krakow, Poland
  • Work
    Senior Software Engineer
  • Joined

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

Thread Thread
 
parthasutradhar profile image
Partha Sutradhar
I'm a Software Engineer with a strong experience that involves in JVM/CLR based technology and machine learning. Besides programming, I have an immense amount of interest in music.
  • Location
    Dhaka, Bangladesh
  • Pronouns
    He / Him
  • Joined
• Edited on• Edited

Yes, Step Builder will force client to provide datum.

Thread Thread
 
siy profile image
Sergiy Yevtushenko
Writing code for 35+ years and still enjoy it...
  • Location
    Krakow, Poland
  • Work
    Senior Software Engineer
  • Joined

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

CollapseExpand
 
masum profile image
Abdullah Al Masum
  • Email
  • Location
    Dhaka, Bangladesh
  • Education
    Completed B.Sc in CSE from MIST, Bangladesh
  • Work
    Software Engineer at Apurba Technologies Ltd
  • Joined

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

CollapseExpand
 
parthasutradhar profile image
Partha Sutradhar
I'm a Software Engineer with a strong experience that involves in JVM/CLR based technology and machine learning. Besides programming, I have an immense amount of interest in music.
  • Location
    Dhaka, Bangladesh
  • Pronouns
    He / Him
  • Joined

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

CollapseExpand
 
pathus90 profile image
Diallo Mamadou Pathé
Software Engineer | Passionate about F1, Startups & Tech | Exploring the intersections of innovation & societal impact
  • Location
    Paris
  • Work
    Full stack developer at V02 GROUP
  • Joined

Nice article.
Lombok has an annotation@builder.

Might be usefull And can reduce boilerplate code

CollapseExpand
 
parthasutradhar profile image
Partha Sutradhar
I'm a Software Engineer with a strong experience that involves in JVM/CLR based technology and machine learning. Besides programming, I have an immense amount of interest in music.
  • Location
    Dhaka, Bangladesh
  • Pronouns
    He / Him
  • Joined

Thanks Pathe. Will try using this from now on.

CollapseExpand
 
khair_al_anam profile image
Khair Alanam
I dabble on everything that is web and design, and maybe a bit of programming. Tea connoisseur. Plays Minecraft. Loves reading a flip load of self-help books.
  • Email
  • Location
    Calicut, Kerala
  • Education
    NIT Rourkela
  • Pronouns
    He/Him
  • Work
    Developer and Designer
  • Joined

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.

CollapseExpand
 
parthasutradhar profile image
Partha Sutradhar
I'm a Software Engineer with a strong experience that involves in JVM/CLR based technology and machine learning. Besides programming, I have an immense amount of interest in music.
  • Location
    Dhaka, Bangladesh
  • Pronouns
    He / Him
  • Joined

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

CollapseExpand
 
anupamakib profile image
Mir Anupam Hossain Akib
Programmer, Software Engineering student, Problem Solver
  • Email
  • Location
    Dhaka, Bangladesh
  • Education
    Daffodil International University
  • Joined

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

CollapseExpand
 
parthasutradhar profile image
Partha Sutradhar
I'm a Software Engineer with a strong experience that involves in JVM/CLR based technology and machine learning. Besides programming, I have an immense amount of interest in music.
  • Location
    Dhaka, Bangladesh
  • Pronouns
    He / Him
  • Joined

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

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

I'm a Software Engineer with a strong experience that involves in JVM/CLR based technology and machine learning. Besides programming, I have an immense amount of interest in music.
  • Location
    Dhaka, Bangladesh
  • Pronouns
    He / Him
  • Joined

More fromPartha Sutradhar

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp