Learn R Programming

FastUtils (version 0.2.1)

validateObject: Validate Object

Description

This function validates an object using a list of checks. If any check fails, an error handler is called and a default value is returned. This function is intended to slightly simplify cases where a long list of complex and convoluted predetermined checks are needed. For simpler cases like type checking, it is recommended to use stopifnot() or assertthat::assert_that().

Usage

validateObject(obj, checks, errorHandler = warningp, defaultReturn = NULL)

Value

The original object if all checks pass, or defaultReturn if any check fails.

Arguments

obj

The object to validate.

checks

A single function or list of functions, each taking the object as an argument and returning NULL if the check passes or an error message if the check fails.

errorHandler

A function to handle errors, taking the error message as an argument. Default is warning.

defaultReturn

The value to return if any check fails. Default is NULL.

Examples

Run this code
# Define some checks
checkNotNull <- function(x) if (is.null(x)) "Object is NULL" else NULL
checkIsNumeric <- function(x) {
    if (!is.numeric(x)) "Object is not numeric" else NULL
}

# Validate an object
obj <- 42
validateObject(obj, list(checkNotNull, checkIsNumeric))

# Validate an object that fails a check
obj <- NULL
try(
    validateObject(
        obj,
        list(checkNotNull, checkIsNumeric, errorHandler = stop)
    ),
    silent = TRUE
)

Run the code above in your browser using DataLab