Builder design pattern in Java with example.

The Builder design pattern is a creational pattern that helps limit an objects complexity. This helps immensely with immutable objects with tons of properties in your application. Immutable objects are objects that don’t change, once you create them, you can’t change them. A immutable Java object must have private final fields. You would also instantiate the object and provide all of the properties in the constructor. This means you won’t use setters to set the properties in the object. This becomes a problem when you have multiple properties and only a few are required. Lets look at a quick example.

Say you have an Employee class with five properties (id, firstName, lastName, title, birthdate) in which you want immutable. Let’s also say that you can instantiate an Employee object while only specifying the id. This would require two constructors, one that takes in all of the properties and one that takes in the id only. This can go on and can get quite messy, especially when more properties are added to the Employee object

This is when the Builder design pattern comes in handy. Lets convert this class into a builder class in steps.

public class Employee {
    
    //properties that are only accessible within the Employee class
    private final int id;
    private final String firstName;
    private final String lastName;
    private final String title;
    private final String birthdate;

    //Constructor that takes in an id only. We still have to set the other properties.
    public Employee(int id){
        this.id = id;
        this.firstName = "";
        this.lastName = "";
        this.title = "";
        this.birthdate = "";
    }
    
    //Constructor that takes in id, firstname, and lastname
    public Employee(int id, String firstName, String lastName) {
        this.id = id;
        this.firstName = firstName;
        this.lastName = lastName;
        this.title = "";
        this.birthdate = "";
    }

    //Constructor that takes in all properties.
    public Employee(int id, String firstName, String lastName, String title, String birthDate) {
        this.id = id;
        this.firstName = firstName;
        this.lastName = lastName;
        this.title = title;
        this.birthdate = birthDate;
    }
}

1. Let’s remove the constructors except for the main constructor that takes in a Builder object and assign the variables like so. The builder object will contain all of the properties in the Employee which we will create next. We will also make the constructor private.

public class Employee {

    private final int id;
    private final String firstName;
    private final String lastName;
    private final String title;
    private final String birthdate;

    private Employee(Builder builder) {
        this.id = builder.id;
        this.firstName = builder.firstName;
        this.lastName = builder.lastName;
        this.title = builder.title;
        this.birthdate = builder.birthDate;
    }
}

2. Add a static inner class within Employee called Builder. Add all the properties and only make the id final because it will be set in the constructor. We then create setters within the builder class that we can only set when we create the object, I will demonstrate that shortly. The build() method will return the Employee object that we put together.

public class Employee {

    private final int id;
    private final String firstName;
    private final String lastName;
    private final String title;
    private final String birthdate;

    private Employee(Builder builder) {
        this.id = builder.id;
        this.firstName = builder.firstName;
        this.lastName = builder.lastName;
        this.title = builder.title;
        this.birthdate = builder.birthDate;
    }

    public static class Builder {
        private final int id;
        private String firstName;
        private String lastName;
        private String title;
        private String birthdate;

        public Builder(int id) {
            this.id = id;
        }

        public Builder setFirstName(String firstName) {
            this.firstName = firstName;
            return this;
        }

        public Builder setLastName(String lastName) {
            this.lastName = lastName;
            return this;
        }

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

        public Builder setBirthDate(String birthDate) {
            this.birthdate = birthDate;
            return this;
        }

        public Employee build() {
            return new Employee(this);
        }
    }
}

3. Add your getters to the Employee class so you can access any of the properties.

public class Employee {

    private final int id;
    private final String firstName;
    private final String lastName;
    private final String title;
    private final String birthdate;

    private Employee(Builder builder) {
        this.id = builder.id;
        this.firstName = builder.firstName;
        this.lastName = builder.lastName;
        this.title = builder.title;
        this.birthdate = builder.birthDate;
    }

    public int getId() {
        return id;
    }

    public String getFirstName() {
        return firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public String getTitle() {
        return title;
    }

    public String getBirthdate() {
        return birthdate;
    }

    public static class Builder {
        private final int id;
        private String firstName;
        private String lastName;
        private String title;
        private String birthDate;

        public Builder(int id) {
            this.id = id;
        }

        public Builder setFirstName(String firstName) {
            this.firstName = firstName;
            return this;
        }

        public Builder setLastName(String lastName) {
            this.lastName = lastName;
            return this;
        }

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

        public Builder setBirthDate(String birthDate) {
            this.birthDate = birthDate;
            return this;
        }

        public Employee build() {
            return new Employee(this);
        }
    }
}


4. Now lets build your objects! In the main method, create new Employee objects like so. You will build the Employee objects at one time and set whatever properties you want. The only required property is the id and that will be passed into the constructor. .build() will return the Employee object that you created! Once you create your employee object, you will not be able to set properties which makes it immutable!

public class Main {

    public static void main(String[] args) {
        Employee employee = new Employee.Builder(1)
                .setFirstName("Tom")
                .setLastName("Brady")
                .build();

        System.out.println("Employee Id: " + employee.getId());
        System.out.println("Employee Name: " + employee.getFirstName() + " " + employee.getLastName());

        Employee employee2 = new Employee.Builder(2)
                .setFirstName("Peyton")
                .setLastName("Manning")
                .setBirthDate("01-01-1976")
                .setTitle("Quarterback")
                .build();

        System.out.println("Employee Id: " + employee2.getId());
        System.out.println("Employee Name: " + employee2.getFirstName() + " " + employee2.getLastName());
        System.out.println("Employee Birthdate: " + employee2.getBirthdate());
        System.out.println("Employee Title: " + employee2.getTitle());

    }
}


Try creating your own objects to get a better understanding. When you want to add a new property, salary for example, you would have to add it to the Employee class, the constructor, Builder class, and your getter/setter.

public class Employee {

    private final int id;
    private final String firstName;
    private final String lastName;
    private final String title;
    private final String birthdate;
    //new property
    private final int salary;

    private Employee(Builder builder) {
        this.id = builder.id;
        this.firstName = builder.firstName;
        this.lastName = builder.lastName;
        this.title = builder.title;
        this.birthdate = builder.birthDate;
        //new property
        this.salary = builder.salary;
    }

    public int getId() {
        return id;
    }

    public String getFirstName() {
        return firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public String getTitle() {
        return title;
    }

    public String getBirthdate() {
        return birthdate;
    }

    //new getter for salary
    public int getSalary() {
        return salary;
    }

    public static class Builder {
        private final int id;
        private String firstName;
        private String lastName;
        private String title;
        private String birthDate;
        //salary property
        private int salary;

        public Builder(int id) {
            this.id = id;
        }

        public Builder setFirstName(String firstName) {
            this.firstName = firstName;
            return this;
        }

        public Builder setLastName(String lastName) {
            this.lastName = lastName;
            return this;
        }

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

        public Builder setBirthDate(String birthDate) {
            this.birthDate = birthDate;
            return this;
        }

        //new setter for salary
        public Builder setSalary(int salary) {
            this.salary = salary;
            return this;
        }

        public Employee build() {
            return new Employee(this);
        }
    }
}
Advertisement

How to run 2 timers on the same TimerTask at different delays in Java.

Lets say you want to run a process on a timer at a random time between 0-5 minutes, but then once that process is complete, you want to run the same process again after 5 minutes?  I have a easy solution for you to try out. All you will use is the java.util.Timer and TimerTask libraries.

1. Create a class that extends TimerTask, in this case I will create TestTimerTask.java.

2. Add the following code. We are creating a Timer property that we will pass into the constructor. Then we create a startTimer method that will purge the prior task, then schedule a new task in 5 minutes (300000 ms) with a new instance of TestTimerTask and Timer.  Once run is complete, startTimer is called, and will execute the same run method in approximately 5 minutes.


import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

public class TestTimerTask extends TimerTask {

    Timer timer;

    public TestTimerTask(Timer timer){
        this.timer = timer;
    }

    public void startTimer(){
        this.timer.purge();
        timer = new Timer();
        timer.schedule(new TestTimerTask(timer), 300);
    }

    @Override
    public void run() {
        try{
            Thread.sleep(500);
        } catch (Exception e) {
            e.printStackTrace();
        }
        startTimer();
    }
}

3. In your main method, create a Timer instance and TestTimerTask instance and pass in a new timer. Then schedule a task with a random time between 0-5 mins (0-600000ms).
This is a quick and easy solution that will help you solve the problem above. I tried other solutions but could not accomplish my scenario. If anyone has a cleaner solution please let me know in the comments below!

import java.util.Random;
import java.util.Timer;

public class Main {

    public static void main(String[] args) {
        Timer timer = new Timer();
        TestTimerTask task = new TestTimerTask(timer);
        timer.schedule(task, new Random().nextInt(600000));
    }
}

How to add DNS to heroku app with GoDaddy.

Prerequisites

  1. Heroku App already deployed. ex url: something.herokuapp.com
  2. GoDaddy domain
Steps

1. In GoDaddy, select the domain you want to configure.
2. Under Domain Settings, Scroll down and select Manage DNS.


3. Under Records you will see CNAME, edit that CNAME and replace @ with your heroku domain under value. If CNAME is not there, add a new CNAME record.

4. Go to Heroku and go to your app settings. Scroll down to Domains and Certificates. Add your GoDaddy domain twice, once with www and once without. 

5. Go to your domain and you site should appear, if not, try clearing your cache and cookies. 

How to highlight text in a Rich Text Editor (QuillJS) and display on screen.

I recently participated in a hack-a-thon and worked on a annotation tool. The front end purpose of the tool was to highlight entities such as “Organizations”, “Locations” and “People”. I used a free rich text editor called Quill JS with KnockoutJS to easily highlight text with your curser and display on the screen above. This is only the tip of the iceberg as Quill is so powerful and contains many different api calls that can be used. You can use any front-end UI framework you prefer, but in this case I will use Knockout JS.

See Codepen for live example.
1. Include the cdn for KnockoutJS and QuillJS. Create the editor container and include the js file you will be loading from. I set an inline style for max-height so it won’t take up the entire page.
 <head>
        <link href="https://cdn.quilljs.com/1.3.6/quill.snow.css" rel="stylesheet">
        <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
 </head>
 <body>
      <div id="editor" style="max-height: 500px">
        <p>Hello World! My name is George, this is text that can be highlighted.</p>
        <p><br></p>
      </div>
      
      <script src="https://cdn.quilljs.com/1.3.6/quill.js"></script>
      <script src="script.js"></script>
 </body>
2. Create the ViewModel and the observable, Initialize the Quill Editor, and add the function that will be called when there is an action to the RTE, in this case, highlighted.
function ViewModel(){
    var self = this; 
    //Create an observable array to display the text that you highlight with your cursor.
    self.selectedText = ko.observableArray([]);
    
     //Initialize the Quill Editor
    var quill = new Quill('#editor', {
        theme: 'snow'
      });

    //This function will be called when you make a change in the text, in this case, highlighting a word. 
    quill.on('selection-change', function(range, oldRange, source){
        //This will get the text range that you highlighted.
        var text = quill.getText(range.index, range.length);
        //This changes the text to bold.
        quill.formatText(range.index, range.length, 'bold', true);
        self.selectedText.push(text);
    })
}
ko.applyBindings(new ViewModel());
3. Add a basic unordered list with a data-bind to display that data when it is highlighted, and that’s it!
<body>
    <ul data-bind="foreach: selectedText">
        <li data-bind="text: $data"></li>
    </ul>
    <div id="editor" style="max-height: 500px">
        <p>Hello World! My name is George, this is text that can be highlighted.</p>
        <p><br></p>
      </div>
</body>