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

3

10

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?

Carabiniere answered 4/5, 2012 at 3:52 Comment(0)
F
5

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

Fredrika answered 4/5, 2012 at 6:9 Comment(0)
C
4

See ?stopifnot

or

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

Conformist answered 4/5, 2012 at 9:29 Comment(0)
R
3

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.

Relinquish answered 4/5, 2012 at 8:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.