validate_arguments: Validate the Type of Input Arguments

View source: R/decorator-validate_arguments.R

validate_argumentsR Documentation

Validate the Type of Input Arguments

Description

Wrap a function with a input validation.

Usage

validate_arguments(func)

Arguments

func

(function) A function to decorate.

Details

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.

How It Works

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.

When to Use It

  • To protect functions from receiving unexpected types of input arguments.

  • In ValueObjects.

Examples: Functions with Built-in NA classes

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`!

Value

(closure) An object that contains the original function bound to the environment of the decorator.

Note

The original function must have default values of the designated type.

References

Examples

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


decorators documentation built on Sept. 30, 2022, 5:06 p.m.