Packages for Assertive Programming

Joe Thorley

2019-04-24

Assertive programming follows the principles of fail fast and fail visibly. It is implemented by issuing an informative error message if the function arguments fail to satisfy specific criteria. This is particularly important in R because it is a dynamically typed language.

There are a host of R packages to facilitate assertive programming. Here I am interested in those packages that are

  1. on CRAN;
  2. lightweight (few or no dependencies);
  3. can be used to test the types and values of common R objects (not just data frames);
  4. issue error messages.

The most useful packages that I am aware of that satisfy these criteria are

This vignette consists of an overview of each package followed by a comparison.

In short the checkr package is recommended over the alternatives if you are looking for a set of expressive, light-weight, pipe-friendly assertive functions with customizable object names.

Package Overview

base

The base package offers the stopifnot() function.

The error message is not that helpful if the user doesn’t know what is.character() tests for.

In a function it behaves as follows:

assertthat

The assertthat package offers assert_that().

The error message is a big improvement on stopifnot()’s.

In a function it behaves as follows:

Perhaps the neatest feature is the ability to set your own error message for an assertion function using on_failure().

checkmate

The checkmate package provides a plethora of functions to check the type and related properties of common objects.

In a function it behaves as follows

In addition, the assert() function allows multiple alternative check** functions (those which return a string of the error message on failure and a TRUE on success) to be combined into one assertion.

checkr

The checkr package provides a set of expressive functions to test the values of objects.

In a function it behaves as follows:

And multiple alternative checks can be combined using the checkor() function.

Package Comparison

Return Values

If all checks are passed stopifnot() returns an invisible NULL, while assert_that() returns TRUE. In contrast, checkmate::assert_** and checkr::check_** return a copy of the original object which allows them to be used in pipes.

Custom Error Messages

Although there is no way to customize the error message produced by stopifnot(), assert_that() allows the programmer to specify the message for a individual test using the msg argument. In the case of checkmate and checkr the programmer can specify the variable name using the .var.name and x_name argument, respectively. This can be very helpful in functions.

Speed

Much of the checkmate package is written in C to minimize execution time.

Dependencies

Whereas the checkmate package depends on backports and utils, and assertthat depends on tools, and checkr depends on err only base is dependency-free.