Builder

Builder design pattern is to parse a long / complex raw data and then construct the data structure out using converters. Hence, it has the name: "builder". The raw data can be sophisticated string joint with comma or configuration files in a particular format. The diagram is as follows:

When to Use (Problem)

  • The problem where there is a need to translate different raw data yielded from encapsulated functions.
  • The problem where the configurations or raw data are encapsulated entirely from the program.
  • The problem where the data structure of the raw data are not defined/quantified definitely.

Example (Solution)

Here is an example in Go:

package main

import (
        "fmt"
        "strconv"
        "strings"
)

// Rectangle is the proper data structure
type Rectangle struct {
        Height int
        Width  int
}


// Parse is the builder function, parsing the raw input from user
func Parse(raw string) *Rectangle {
        l := strings.Split(raw, ",")
        r := &Rectangle{
                height: -1,
                width:  -1,
        }
        if l[0] == "r" {
                r.height = convert(l[1])
                r.width = convert(l[2])
                return r
        }
        return nil
}

func convert(value string) int {
        v, err := strconv.Atoi(value)
        if err != nil {
                return -1
        }
        return v
}


// client interaction
func main() {
        r := Parse("r,5,10")
        if r == nil {
                fmt.Printf("r is nil\n")
                return
        }
        fmt.Printf("height: %v, width: %v\n", r.Height, r.Width)
}

// Output:
// height: 5, width: 10

Notice that Parse function's input takes a form of string consisting of 3 different data (r,5,10). It then splits based on its available definition and then pass it to convert for data conversion before assembling the proper data structure.

Once done, the client is able to interact using the proper data structure.

Expected Outcome (Consequences)

  • Encapsulated the ambiguity of the user inputs from the program.
  • Isolate raw data processing from the main program.
  • Defines clearly about the input definition for the main program.