source(file.path(usethis::proj_get(), "vignettes", "_common.R"))
sum()
The function sum()
does one thing -- summing up a numeric vector.
base::sum(1, 2, 3)
If the caller passes sum()
non-numeric values then the function fails.
base::sum(1, "2", 3)
print('Error in base::sum(1, "2", 3) : invalid \'type\' (character) of argument')
Using purrr::compose
, purrr::safely
, and purrr::pluck
, we can alternate
the behaviour of sum()
to produce NA instead of failing:
# Decorating `sum` with failproof mechanism: # 1. Return NA when sum fails # 2. Extract the result sum <- purrr::safely(base::sum, otherwise = NA_real_) sum <- purrr::compose(sum, ~ purrr::pluck(.x, "result"), .dir = "forward")
With the decorated sum()
function, the behaviour for non-numeric values alters
sum(1, 2, 3) sum(1, "2", 3)
The decorated sum()
function is (a) failproof and (b) requires no changes in the codebase -- without it, a programmer would have encapsulated sum()
instances with tryCatch
statement
such as this:
tryCatch(sum(x), error = function(e) return(NA_real_))
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.