0% found this document useful (0 votes)
61 views

Introduction To The Fluent Builder Pattern - DZone Java

The document introduces the fluent builder pattern, which is a coding style that forces developers to build complex objects in sequence by calling setter methods one after another until all required attributes are set. It explains how to implement a fluent builder by creating an interface chain where each interface method returns the next interface type, and providing an example of building an Email object using this pattern. The fluent builder pattern helps avoid mistakes by making it mandatory to set all required fields before building the final object.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
61 views

Introduction To The Fluent Builder Pattern - DZone Java

The document introduces the fluent builder pattern, which is a coding style that forces developers to build complex objects in sequence by calling setter methods one after another until all required attributes are set. It explains how to implement a fluent builder by creating an interface chain where each interface method returns the next interface type, and providing an example of building an Email object using this pattern. The fluent builder pattern helps avoid mistakes by making it mandatory to set all required fields before building the final object.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

3/9/2021 Introduction to the Fluent Builder Pattern - DZone Java

(/)  (/users/login.html)  (/search)

REFCARDZ (/refcardz) RESEARCH (/research) WEBINARS (/webinars) ZONES 

(https://d2u6dc21frjf6h.cloudfront.net/d/3eJydUMtOwzAQ/BXLh55w8wKVVoqQmwYubUnpIXCKXMdKLBI7xHaLQPw73kgIzuxhpd2dmR3NJx7xCuHW2sGsgoBdzJz17E
n=1)

DZone (/) > Java Zone (/java-jdk-development-tutorials-tools-news) > Introduction to the Fluent Builder Pattern

Introduction to the Fluent Builder Pattern


(/users/1396883/milind.d.html) by Milind Deobhankar (/users/1396883/milind.d.html)  CORE · Jun. 14, 19 · Java Zone (/java-jdk-

development-tutorials-tools-news) · Presentation

 Like (13)  Comment (3)  Save  Tweet

The fluent builder pattern is one of the most useful patterns, especially when you want to build complex objects. For example, say you want
to build a complex object by initiating the builder, calling the respective setters, and finally, calling the build method. Once the build method
is executed, you will get the desired model/entity/pojo object back.

1 Email email = Email.EmailBuilder()


2 .setFrom("[email protected]")
3 .setTo("[email protected]")
4 .setSubject("Test with only required Fields")
5 .setContent(" Required Field Test").build();

This looks quite simple but there is one catch. If the object building is complex and there are too many setters methods, then normally the
developer's tendency is to forget some of the setters and build the object. Doing so, many of the important object attributes will be null, and
so, no setters are being called for the same.

In many enterprise applications, there will be a core entity like Order/Loan, and it might get initiated in many sections of the code, missing
the set attribute can be a costly process in terms of development and maintenance. So, what do you do?

The answer is to force the developer to set all required setter methods before calling the build method. Doing so, all required attributes will
get initialized and build object is in your desired state. But how to force the developer? The answer is through the fluent builder pattern.

What Is the Fluent Builder Pattern?

Fluent builder pattern is a style of coding which force the developer to create the object in
sequence by calling each setter method one after the another until all required attributes are set.

Let’s go in detail about how to achieve the fluent builder pattern. The fluent builder pattern is similar to any fluent API call, but this is used
to build the object. For achieving fluent builder, we are going to create an interface chain where each interface method will return the next
interface type. Confused? Let me explain with an example. For the sake of simplicity, we will try to build the Email Object, which will
contain all the info to send the email.

1 public final class Email {


2
3 // To Address. Multiple Address separated by ","
4 String to;
5 //From Address
6 String from;
7 // Subject of the email
8 String subject;
9 // Content of the email
10 String content;
11 // BCC optional
12 String bcc;
13 // CC Optional
14 String cc;
https://dzone.com/articles/fluent-builder-pattern 1/4
3/9/2021 Introduction to the Fluent Builder Pattern - DZone Java
15 }
(/)  (/users/login.html)  (/search)
Let’s define the mandatory and optional attributes. Mandatory attributes are from,to,subject and content. Optional attributes are cc and bcc.
REFCARDZ (/refcardz) RESEARCH (/research) WEBINARS (/webinars) ZONES 
Here we need to create interface chain for the setting the attributes as follow:

1 // Interface to Set From


2 interface EmailFrom {
3 EmailTo setFrom(String from);
4 }
5 //Interface to Set To
6 interface EmailTo {
7 EmailSubject setTo(String to);
8 }
9 //Interface to Set subject
10 interface EmailSubject {
11 EmailContent setSubject(String subject);
12 }
13 // Interface to set Content
14 interface EmailContent {
15 EmailCreator setContent(String content);
16 }
17 // Final Email Creator Class
18 interface EmailCreator {
19
20 EmailCreator setBCC(String bcc);
21 EmailCreator setCC(String cc);
22 Email build();
23 }
24

If you see for each attribute that there is one interface and one method, the return type of the method is the next interface in the sequence.
Creating the builder class is easy, it needs to implement all our interfaces defined as part of the interface chain as follows:

1 public static class EmailBuilder implements EmailFrom, EmailTo,


2 EmailSubject, EmailContent, EmailCreator{
3
4 String to;
5 String from;
6 String subject;
7 String content;
8 String bcc;
9 String cc;
10
11 /**
12 * Private emailbuilder to prevent direct object creation
13 */
14 private EmailBuilder(){
15 }
16
17 /**
18 * Getting the instance method
19 * @return
20 */
21 public static EmailFrom getInstance(){
22 return new EmailBuilder();
23 }
24 ...
25 }

We need to provide the instance method for the builder and make the constructor private so that the developer is forced to create the builder
object as we want. Another important point is that the instance method should return the first interface type in the chain. For any optional
attribute that is required, we need to create methods in the last interface in the chain along with the build method.

Let's create the Email Object with only mandatory and non-mandatory attributes as follows:

1 //Creating basic email object without cc and bcc


2 Email email = Email.EmailBuilder.getInstance().setFrom("[email protected]").setTo("[email protected]")
3 .setSubject("Test with only required Fields").setContent(" Required Field Test").build();
4
5 System.out.println(email);
6
7 //Creating the full Email Object with cc and bcc
https://dzone.com/articles/fluent-builder-pattern 2/4
3/9/2021 Introduction to the Fluent Builder Pattern - DZone Java
7 //Creating the full Email Object with cc and bcc
8 email = Email.EmailBuilder.getInstance().setFrom("[email protected]").setTo("[email protected]")
9 
(/).setSubject("Test with ALL Fields").setContent(" ALL Field Test").setBCC("[email protected]")
(/users/login.html)  (/search)
10 .setCC("[email protected]").build();
REFCARDZ
11 (/refcardz) RESEARCH (/research) WEBINARS (/webinars) ZONES 
12 System.out.println(email);

Conclusion
If your requirement is to build a complex object for which you want to set the mandatory attributes and avoid making any mistakes, then the
fluent builder will be more useful rather than the traditional builder pattern.

You can find the entire code here. (https://github.com/MilindAtGithub/fluentbuilder)

Topics: DESIGN PATTERN, JAVA, FLUENT BUILDER PATTERN, TUTORIAL, CODE, EXAMPLE

Published at DZone with permission of Milind Deobhankar. See the original article here.  (https://blogmilind.wordpress.com/2019/05/02/fluent-
builder-pattern/)
Opinions expressed by DZone contributors are their own.

Popular on DZone
Partitioning MySQL: Why, When, How? (/articles/partitioning-mysql-why-when-how?fromrel=true)

Top 10 Codeless Testing Tools For 2021 (/articles/top-10-codeless-testing-tools-for-2021?fromrel=true)

AWS Cloud Migration: How To Determine First-Mover Workloads (/articles/aws-cloud-migration-how-to-determine-first-mover-w-1?


fromrel=true)

Transformations of Varying JSON Payloads Using Spark-Streaming (/articles/Transformations-of-Varying-JSON-Payloads-using-Spark-


Streaming?fromrel=true)

ABOUT US
About DZone (/pages/about)
Send feedback (mailto:[email protected])
Careers (https://devada.com/careers/)
Sitemap (/sitemap)

ADVERTISE
Advertise with DZone (/pages/advertise)
+1 (919) 238-7100 (tel:+19192387100)

CONTRIBUTE ON DZONE
Article Submission Guidelines (/articles/dzones-article-submission-guidelines)
MVB Program (/pages/mvb)
Become a Contributor (/pages/contribute)
Visit the Writers' Zone (/writers-zone)

LEGAL
Terms of Service (/pages/tos)
Privacy Policy (/pages/privacy)

CONTACT US
600 Park Offices Drive
Suite 300
Durham, NC 27709
[email protected] (mailto:[email protected])
+1 (919) 678-0300 (tel:+19196780300)

Let's be friends:    
(/pages/feeds)
(https://twitter.com/DZoneInc)
(https://www.facebook.com/DZoneInc)
(https://www.linkedin.com/company/dzone/)

DZone.com is powered by (https://devada.com/answerhub/)

https://dzone.com/articles/fluent-builder-pattern 3/4
3/9/2021 Introduction to the Fluent Builder Pattern - DZone Java

https://dzone.com/articles/fluent-builder-pattern 4/4

You might also like