Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the idiomatic way to check and document function preconditions and postconditions in R?

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?

like image 283
fmark Avatar asked May 04 '12 03:05

fmark


3 Answers

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

like image 79
mdsumner Avatar answered Sep 22 '22 09:09

mdsumner


See ?stopifnot

or

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

like image 36
G. Grothendieck Avatar answered Sep 21 '22 09:09

G. Grothendieck


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.

like image 45
Paul Hiemstra Avatar answered Sep 20 '22 09:09

Paul Hiemstra