Sitemap

Builder Design Pattern— Client Perspective

4 min readMar 25, 2017

--

Almost every software code base may be using builder design pattern. It helps to create complex object by separating its representation. Same construction process can create different representations. (See more)

We know that its for building “complex” objects. Complexity increases with number of optional fields as such optional fields needs to be checked for existence before getting values from it.

Article focuses on implementation of Builder from its client perspective to make its life easier with many optional fields. Sometimes complexity is passed over to client or Builder has code that is not easy to maintain.

Evolving to Builder

Let’s see example where developer decides to use Builder pattern. A Book object creation. Book is defined as follows:

class Book {
private String title; // Required
private String author; // Required

/**
* This is optional as some books are not for sale.
* Yes, there are!
*/
private int price;

// Other optional fields to follow.
}

After applying Builder pattern, one may end up with this structure:

class Book {
private String title;
private String author;
private int price;

private Book(Builder builder) {
title = builder.title;
author = builder.author;
price = builder.price;
}

String getTitle() {
return title;
}

String getAuthor() {
return author;
}

int getPrice() {
return price;
}

static class Builder {
private String title;
private String author;
int price;

Builder setTitle(String title) {
this.title = title;
return this;
}

Builder setAuthor(String author) {
this.author = author;
return this;
}

Builder setPrice(int price) {
this.price = price;
return this;
}

Book build() {
if (isInvalid()) {
throw new IllegalArgumentException("Title and author is required");
}
return new Book(this);
}

boolean isInvalid() {
return title == null || author == null || title.isEmpty() || author.isEmpty();
}
}
}

Corresponding Client code:

public class Client {
public static void main(String[] args) {
Book harryPotterPart1 = new Book.Builder()
.setTitle("Harry Potter - Part 1")
.setAuthor("J K")
.setPrice(100)
.build();

Book freeEbook = new Book.Builder()
.setTitle("Free Ebook - Design Patterns")
.setAuthor("GoF")
.setPrice(0)
.build();

Book productsBook = new Book.Builder()
.setTitle("Company products")
.setAuthor("XYZ Pvt. Ltd")
.build(); // Book with no price tag.

printBookPrice(harryPotterPart1);
printBookPrice(freeEbook);
printBookPrice(productsBook);
}

private static void printBookPrice(Book book) {
System.out.println("Book title " + book.getTitle());
System.out.println("Book Price : " + book.getPrice());
}

Problem with above builder is : Client cannot reliably determine whether book is free or not for sale. Because, default value of int is zero and free books price is also zero.

Various alternatives to get rid of this ambiguity for optional fields are: Setting known default value, Using Wrapper classes for primitive variables, using boolean state variables and recommended one.

Setting known default value

One may quickly think and set it as -1 to distinguish between two states. May be that is sufficient for today. And client code will be changed like this:

priceToPrint = book.getPrice() == -1
? "Not for Sale"
: "" + book.getPrice();

Now, lets assume that one generous book shop owner decides to give very old and good books to frequent book buyers with cashback of same price with condition of buying one new book along with it. That’s affordable to him because old books has low price compared to current times.

So, price of “old and good book” can be negative and so logic of using -1 is no more valid. Client will not determine difference again.

Using Wrapper classes

Wrapper class object (which can be null) for primitive variables. So, instead of using optional variable as

private int price;

one can use

private Integer price;

And client code will become

priceToPrint = book.getPrice() == null
? "Not for Sale"
: "" + book.getPrice();

This solves problem for primitive types but its not generic enough to accomodate other optional fields of type like String. Because, null can be valid value for such optional fields.

Get Sachin Patil’s stories in your inbox

Join Medium for free to get updates from this writer.

Boolean state variables

What if we use boolean variable to track whether ‘price is set or not’ using builder API. Excerpt from code with this change :

class Book {

.....

private int price;
private boolean isPriceSet; // boolean state variable for price

private Book(Builder builder) {
....
price = builder.price;
isPriceSet = builder.isPriceSet;
}

// This is new API to simplifiy client code.
boolean hasPrice() {
return isPriceSet;
}

int getPrice() {
return price;
}

static class Builder {
..... private int price;
private boolean isPriceSet;
Builder setPrice(int price) {
this.price = price;
isPriceSet = true;
return this;
}
..... }
}

Client code now:

priceToPrint = book.hasPrice()
? "" + book.getPrice()
: "Not for Sale";

As we can see, client code is simplified. It can easily determine whether price is set or not. However, code in Builder and Book will get cluttered with lot of booleans as soon as there are many optional variables similar to price. Every boolean state variable needs to be passed from Builder to Book.

A Flag for all fields (Recommended)

Builder can be simplified using byte/short/int variable as flag with every bit in it reserved for boolean state variables for optional fields.

class Book {    .....    private int price;
private static byte PRICE_FLAG = 0x1;

private byte fieldsFlag; // common flag for optional fields

private Book(Builder builder) {
title = builder.title;
author = builder.author;
price = builder.price;
fieldsFlag = builder.fieldsFlag;
}
.... boolean hasPrice() {
return hasFlag(PRICE_FLAG);
}

private boolean hasFlag(byte flag) {
return flag == (fieldsFlag & flag);
}

int getPrice() {
return price;
}

static class Builder {
.....
private int price;
private byte fieldsFlag;

....
Builder setPrice(int price) {
this.price = price;
setFlag(PRICE_FLAG);
return this;
}

private void setFlag(byte flag) {
fieldsFlag = (byte) (fieldsFlag | flag);
}

.....
}
}

Code in Builder/Book is lot readable and more maintainable after above change. Client code does not require null or default value checks as well.

Conclusion

Passing single flag from Builder for all optional fields has advantages of keeping Builder, its target object and client code maintainable, readable and efficient. Solution is generic enough to apply in all situations for Builder pattern. It is recommended where many fields are optional in target object getting created.

If you liked this article, please hit the ❤ icon below and follow me. Leave comment :)

--

--

Sachin Patil
Sachin Patil

Written by Sachin Patil

Loves coding, travelling, hiking, reading a lot everyday