Question

What is the idiomatic way to check and document function preconditions and postconditions in R? I would consider Eiffel's built in require and ensure constructs or D's in and out blocks state of the art here, but most languages don't have these baked in so have developed best practices to approximate them.

By checking preconditions, I mean throwing some kind of runtime exception if data that doesn't meet the functions assumptions are passed in. Currently have a stopifnot statement for every precondition I can think of at the start of the function. The same applies for postconditions, but with respect to the return value rather than the parameters.

Furthermore, is there are standard way of documenting what these preconditions and postconditions are? For example, it is pretty standard to spell these out in JavaDoc comments in Java.

What are the best practices in R in this respect?

Was it helpful?

Solution

Validity checking for S4 classes, where the checks are stored with the class definition via 'setValidity'. See for example:

http://www.r-project.org/conferences/useR-2004/Keynotes/Leisch.pdf

OTHER TIPS

See ?stopifnot

or

for friendlier error messages but more verbose code if (condition) stop("...message...") .

In terms of documentation I would recommend you take a look at the roxygen2 package. It is comparable to JavaDoc and Doxygen in that it stores the documentation in the source file together with the code. There are a number of items that need to be defined, e.g.:

  • What are the input arguments
  • What does the function return

But this does not stop you from creating your own pre and post items that document the pre and post conditions. For more info on roxygen2 see CRAN or StackOverflow.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top