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?
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
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.:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With