Menu
Coddy logo textTech

Builder Pattern

Part of the Object Oriented Programming section of Coddy's R journey. Lesson 47 of 57.

A builder assembles a complicated object step by step and creates it at the end with build(). A closure-based builder keeps the parts in private variables; each step returns the builder itself with invisible(self), so the steps chain and a step called on its own prints nothing:

pizza_builder <- function() {
  size <- "medium"
  toppings <- character(0)
  self <- list(
    size = function(s) { size <<- s; invisible(self) },
    add = function(t) { toppings <<- c(toppings, t); invisible(self) },
    build = function() structure(list(size = size, toppings = toppings), class = "pizza")
  )
  self
}
p <- pizza_builder()$size("large")$add("olives")$add("basil")$build()
cat(p$size, "with", paste(p$toppings, collapse = " and "))

Output:

large with olives and basil

build() is the place to check that the object is complete. Missing parts stop with a message instead of producing a half-made object:

email_builder <- function() {
  to <- NULL
  subject <- ""
  self <- list(
    to = function(x) { to <<- x; invisible(self) },
    subject = function(x) { subject <<- x; invisible(self) },
    build = function() {
      if (is.null(to)) stop("an email needs a recipient", call. = FALSE)
      paste0("To: ", to, " | Subject: ", subject)
    }
  )
  self
}
print(email_builder()$to("ada@x.org")$subject("Hi")$build())
print(tryCatch(email_builder()$subject("Hi")$build(), error = function(e) conditionMessage(e)))

Output:

[1] "To: ada@x.org | Subject: Hi"
[1] "an email needs a recipient"

The same idea works with plain values and the pipe |>. Each step is a function that takes the description so far and returns an updated copy, and the last step builds the result:

request <- function(url) list(url = url, method = "GET", headers = character(0))
with_method <- function(req, m) { req$method <- m; req }
with_header <- function(req, name, value) { req$headers[name] <- value; req }
build_request <- function(req) {
  c(paste(req$method, req$url), paste0(names(req$headers), ": ", req$headers))
}
r <- request("/users") |> with_method("POST") |> with_header("Accept", "json") |> build_request()
cat(r, sep = "\n")

Output:

POST /users
Accept: json

A builder replaces a constructor with many optional arguments. Each step names what it sets, and parts that are not mentioned keep their defaults:

# hard to read: what is TRUE, what is 3?
make_report("sales", TRUE, FALSE, 3, "pdf")

# a builder says what each value means
report_builder("sales")$with_totals()$top(3)$format("pdf")$build()
challenge icon

Challenge

Easy

Complete the closure-based query_builder(table) in QueryBuilder.R. Its steps return the builder so they can be chained:

  • select(cols): the columns to show (default *);
  • where(cond): adds a condition; several are joined with AND ;
  • order_by(col) and limit(n);
  • build(): returns the query, such as SELECT name, age FROM users WHERE age > 30 AND city = 'Rome' ORDER BY name LIMIT 5, leaving out the parts that were not set.

The supplied code reads the table, then lines select name age, where age > 30, order name or limit 5, and prints the built query. It then builds a second query in one chain.

Your code goes in QueryBuilder.R. main.R holds the supplied input/output code and cannot be edited.

Try it yourself

source("QueryBuilder.R")

# Supplied input/output code: keep it as it is
input <- suppressWarnings(readLines(file("stdin")))
q <- query_builder(input[1])
for (line in input[-1]) {
  p <- strsplit(line, " ")[[1]]
  rest <- paste(p[-1], collapse = " ")
  if (p[1] == "select") q <- q$select(p[-1])
  if (p[1] == "where") q <- q$where(rest)
  if (p[1] == "order") q <- q$order_by(p[2])
  if (p[1] == "limit") q <- q$limit(as.numeric(p[2]))
}
cat(q$build(), "\n", sep = "")
cat(query_builder("logs")$select("msg")$limit(1)$build(), "\n", sep = "")
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Object Oriented Programming

Practice on your own: Online R compiler