Advanced Builder

Higher Ordered Functions

Background vector created by freepik - www.freepik.com

Disclaimer : The content of this blog are my views and understanding of the topic. I do not intend to demean anything or anyone. I am only trying to share my views on the topic so that you will get a different thought process and angle to look at this topic.

Introduction

Java 8 introduced Functional Programming using Lambdas which enables us to externalise the behaviour (i.e. a function) which now can be passed as an argument to another function. Looks simple but it's a very powerful feature. I was fascinated by this idea and wanted to experiment with it. My experimentation is always based on what language restrictions are and how far can I reach based on my skills, knowledge and creativity. I created something called an Advanced Builder using this. Let's explore how.

We all know that a Builder solves the problem of a telescopic constructor while instantiating an object. In case of constructor with many arguments it's difficult to read quickly which argument is to be passed in which position. IDE tools now-a-days are smart enough to show in the code the parameter names but still there are certain cases when they don't show them. My observation is that they show the parameter names as far as we pass actual values as arguments and not a method call as direct argument. Please see the screenshot below :

Parameter Name shown by IntelliJ Idea

How to solve this problem using Java 8 Lambda and create a builder using the same. Check below code and let's discuss more on this.

Advanced Builder Mutable Object
Advanced Builder Mutable Object Demo

Below are some points to be noted on this :

PROS

CONS

Then I recollected that a friend of mine once wrote a great blog on Advanced Builder Pattern using Lambda. In his approach he used an externalised Builder. I am using the same approach in a different way. I used an Inner Builder Class to achieve the Immutability.

Advanced Builder Immutable Object

Demo Output

Structural Analysis

Structural analysis of the above class reveals :


In simple words we are telling the builder what are the states of the Customer instance which we need to build it with. It takes that and applies it and generates an instance of Customer and returns it back. Now we can create Immutable Objects of Customer with much more readable code.

Final Advanced Builder Demo
Demo Output Final

Summary

Java 8 Lambdas are an addition to the freedom provided to Developers by Java. We can create smarter code and make it more Readable, Reusable and AGILE. I tried experimenting so far to create this Advanced Builder but I am trying to achieve is how can we get rid of this Inner Builder class and have the single constructor in the original class and create Immutable Objects.

KEEP THINKING !!!