source(file.path(usethis::proj_get(), "vignettes", "_common.R"))
cat(knitr::knit_child('./vignettes/details/_NullObject.Rmd', quiet = TRUE))

Example: Null ggplot2

geom_null <- function(...) {
  ggplot2::ggplot() +
    ggplot2::geom_blank() +
    ggplot2::theme_void()
}
fig <-
  tryCatch(
    {
      stopifnot(runif(1) > 0.05) # simulate 5% chance for the subroutine to fail

      mtcars |>
        ggplot2::ggplot(ggplot::aes(x = mpg, y = hp)) +
        ggplot2::geom_point()
    },
    error = function(e) {
      return(geom_null())
    } # if subroutine has failed, return null
  )

plot(fig)
if (exists("user_input")) {
  ggplot2::ggplot(user_input, ggplot::aes(x = mpg, y = hp)) +
    ggplot2::geom_point()
} else {
  geom_null() + geom_text(aes(0, 0), label = "choose an entry from the list")
}

Example: Null mtcars Car

NullCar <- function() mtcars[0, ]
print(NullCar())

# The Null Car and the NULL value are not the same
identical(NullCar(), NULL)

# Binding mtcars with the Null Car returns mtcars
identical(rbind(mtcars, NullCar()), mtcars)

Example: Null Value Object

Person <- function(given = NA_character_, family = NA_character_) {
  tibble::tibble(given = given, family = family) |> tidyr::drop_na(given)
}

# Instantiating a person with a `given` name, returns a non-null person object
print(Person("Madonna"))

# Instantiating a person without a `given` name, returns the null person object
print(Person())

Further Reading

Null Object on Wikipedia



tidylab/R6P documentation built on Dec. 23, 2024, 9:22 a.m.