Wrap a function with a input validation.
validate_arguments(func)
(function
) A function to decorate.
(closure
) An object that contains the original function bound to the environment of the decorator.
validate_arguments
decorator allows the arguments passed to a function
to be parsed and validated using the function’s annotations before the
function is called.
validate_arguments
provides an extremely easy way to apply validation
to your code with minimal boilerplate. The original function needs to
have key-value pairs in its declaration, where the each value carries
its designated class.
To protect functions from receiving unexpected types of input arguments.
In
ValueObjects
.
Given a Customer
ValueObject
Customer <- function(given = NA_character_, family = NA_character_)
return(data.frame(given = given, family = family))
When Customer
is decorated with validate_arguments
Customer <- validate_arguments(Customer)
Then passing arguments of any type other then the declared type prompts an informative error.
In the Customer
example, both input arguments given
and family
are
declared as character
.
Customer(given = "Bilbo", family = "Baggins") # Works as both arguments are character
#> given family
#> 1 Bilbo Baggins
try(Customer(given = "Bilbo", family = 90201)) # Fails because family is not a character
#> Error in Customer(given = "Bilbo", family = 90201) :
#> family is of type `numeric` rather than `character`!
The original function must have default values of the designated type.
Car <- function(model = NA_character_, hp = NA_real_){
return(data.frame(model = model, hp = hp))
}
Car <- validate_arguments(Car)
try(Car(model = 555, hp = 120)) # fails because model is numeric rather than character
#> Error in Car(model = 555, hp = 120) :
#> model is of type `numeric` rather than `character`!