The Ten Rules of Defensive Programming in R
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
What is defensive programming?
The idea of defensive programming is not to write code that never fails. That’s an impossible aspiration. Rather, the fundamental idea is to write code that fails well. To me, ‘failing well’ means five things:
- Fail fast: your code should ensure all criteria are met before they embark upon operations, especially if those are computationally expensive or might irreversibly affect data.
- Fail safe: where there is a failure, your code should ensure that it relinquishes all locks and does not acquire any new ones, not write files, and so on.
- Fail conspicuously: when something is broken, it should return a very clear error message, and give as much information as possible to help unbreak it.
- Fail appropriately: failure should have appropriate effects. For every developer, it’s a judgment call to ensure whether a particular issue would be a a debug/info item, a warning or an error (which by definition means halting execution). Failures should be handled appropriately.
- Fail creatively: not everything needs to be a failure. It is perfectly legitimate to handle problems. One example is repeating a HTTP request that has timed out: there’s no need to immediately error out, because quite frankly, that sort of stuff happens. Equally, it’s legitimate to look for a parameter, then check for a configuration file if none was provided, and finally try checking the arguments with which the code was invoked before raising an error.1
And so, without further ado, here are the ten ways I implement these in my day-to-day R coding practice – and I encourage you to do so yourself. You will thank yourself for it.
The Ten Commandments of Defensive Programming in R
- Document your code.
- In God we trust, everyone else we verify.
- Keep functions short and sweet.
- Refer to external functions explicitly.
- Don’t use
require()
to import packages into the namespace. - Aggressively manage package and version dependencies.
- Use a consistent style and automated code quality tools.
- Everything is a package.
- Power in names.
- Know the rules and their rationale, so that you know when to break them.
ONE: Document your code.
It’s a little surprising to even see this – I mean, shouldn’t you do this stuff anyway? Yes, you should, except some people think that because so much of R is done in the interpreter anyway, rules do not apply to them. Wrong! They very much do.
A few months ago, I saw some code written by a mentee of mine. It was infinitely long – over 250 standard lines! –, had half a dozen required arguments and did everything under the sun. This is, of course, as we’ll discuss later, a bad idea, but let’s put that aside. The problem is, I had no idea what the function was doing! After about half an hour of diligent row-by-row analysis, I figured it out, but that could have been half an hour spent doing something more enjoyable, such as a root canal without anaesthetic while listening to Nickelback. My friend could have saved me quite some hair-tearing by quite simply documenting his code. In R, the standard for documenting the code is called roxygen2
, it’s got a great parser that outputs the beautiful LaTeX docs you probably (hopefully!) have encountered when looking up a package’s documentation, and it’s described in quite a bit of detail by Hadley Wickham. What more could you wish for?
Oh. An example. Yeah, that’d be useful. We’ll be documenting a fairly simple function, which calculates the Hamming distance between two strings of equal length, and throws something unpleasant in our face if they are not. Quick recap: the Hamming distance is the number of characters that do not match among two strings. Or mathematically put,
where is the length function and is the dissimilarity function, which returns 1 if two letters are not identical and 0 otherwise.
So, our function would look like this:
hamming <- function(s1, s2) { s1 <- strsplit(s1, "")[[1]] s2 <- strsplit(s2, "")[[1]] return(sum(s1 != s2)) }
Not bad, and pretty evident to a seasoned R user, but it would still be a good idea to point out a thing or two. One of these would be that the result of this code will be inaccurate (technically) if the two strings are of different lengths (we could, and will, test for that, but that’s for a later date). The Hamming distance is defined only for equal-length strings, and so it would be good if the user knew what they have to do – and what they’re going to get. Upon pressing Ctrl/Cmd+Shift+Alt+R, RStudio helpfully whips us up a nice little roxygen2
skeleton:
#' Title #' #' @param s1 #' @param s2 #' #' @return #' @export #' #' @examples hamming <- function(s1, s2) { s1 <- strsplit(s1, "")[[1]] s2 <- strsplit(s2, "")[[1]] return(sum(s1 != s2)) }
So, let’s populate it! Most of the fields are fairly self-explanatory. roxygen2
, unlike JavaDoc or RST-based Python documentation, does not require formal specification of types – it’s all free text. Also, since it will be parsed into LaTeX someday, you can go wild. A few things deserve mention.
- You can document multiple parameters. Since
s1
ands2
are both going to be strings, you can simply write@param s1,s2 The strings to be compared
. - Use
\code{...}
to typeset something as fixed-width. - To create links in the documentation, you can use
\url{https://chrisvoncsefalvay.com}
to link to a URL,\code{\link{someotherfunction}}
to refer to the functionsomeotherfunction
in the same package, and\code{\link[adifferentpackage]{someotherfunction}}
to refer to the functionsomeotherfunction
in the adifferentpackage package. Where your function has necessary dependencies outside the current script or the base packages, it is prudent to note them here. - You can use
\seealso{}
to refer to other links or other functions, in this package or another, worth checking out. - Anything you put under the examples will be executed as part of testing and building the documentation. If your intention is to give an idea of what the code looks like in practice, and you don’t want the result or even the side effects, you can surround your example with a
\dontrun{...}
environment. - You can draw examples from a file. In this case, you use
@example
instead of@examples
, and specify the path, relative to the file in which the documentation is, to the script:@example docs/examples/hamming.R
would be such a directive. - What’s that
@export
thing at the end? Quite simply, it tellsroxygen2
to export the function to the NAMESPACE file, making it accessible for reference by other documentation files (that’s how when you use\code{\link[somepackage]{thingamabob}}
,roxygen2
knows which package to link to.
With that in mind, here’s what a decent documentation to our Hamming distance function would look like that would pass muster from a defensive programming perspective:
#' Hamming distance #' #' Calculates the Hamming distance between two strings of equal length. #' #' @param s1 #' @param s2 #' #' @return The Hamming distance between the two strings \code{s1} and \code{s2}, provided as an integer. #' #' @section Warning: #' #' For a Hamming distance calculation, the input strings must be of equal length. This code does NOT reject input strings of different lengths. #' #' @examples #' hamming("AAGAGTGTCGGCATACGTGTA", "AAGAGCGTCGGCATACGTGTA") #' #' @export hamming <- function(s1, s2) { s1 <- strsplit(s1, "")[[1]] s2 <- strsplit(s2, "")[[1]] return(sum(s1 != s2)) }
The .Rd file generated from the hamming() function’s roxygen2 docstring: an intermediary format, resembling LaTeX, from which R can build a multitude of documentation outputsThis little example shows all that a good documentation does: it provides what to supply the function with and in what type, it provides what it will spit out and in what format, and adequately warns of what is not being checked. It’s always better to check input types, but warnings go a long way.2 From this file, R generates an .Rd
file, which is basically a LaTeX file that it can parse into various forms of documentation (see left.) In the end, it yields the documentation below, with the adequate warning – a win for defensive programming!
TWO: In God we trust, everyone else we verify.
In the above example, we have taken the user at face value: we assumed that his inputs will be of equal length, and we assumed they will be strings. But because this is a post on defensive programming, we are going to be suspicious, and not trust our user. So let’s make sure we fail early and check what the user supplies us with. In many programming languages, you would be using various assertions (e.g. the assert
keyword in Python), but all R has, as far as built-ins are concerned, is stopifnot()
. stopifnot()
does as the name suggests: if the condition is not met, execution stops with an error message. However, on the whole, it’s fairly clunky, and it most definitely should not be used to check for user inputs. For that, there are three tactics worth considering.
assertthat
is a package by Hadley Wickham (who else!), which implements a range ofassert
clauses. Most importantly, unlikestopifnot()
,assertthat::assert_that()
does a decent job at trying to interpret the error message. Consider our previous Hamming distance example: instead of gracelessly falling on its face, a test using
assert_that(length(s1) == length(s2))
- would politely inform us that
s1 not equal to s2
. That’s worth it for the borderline Canadian politeness alone. - Consider the severity of the user input failure. Can it be worked around? For instance, a function requiring an integer may, if it is given a float, try to coerce it to a float. If you opt for this solution, make sure that you 1) always issue a warning, and 2) always allow the user to specify to run the function in ‘strict’ mode (typically by setting the
strict
parameter toTRUE
), which will raise a fatal error rather than try to logic its way out of this pickle. - Finally, make sure that it’s your code that fails, not the system code. Users should have relatively little insight into the internals of the system. And so, if at some point there’ll be a division by an argument
foo
, you should test whetherfoo == 0
at the outset and inform the user thatfoo
cannot be zero. By the time the division operation is performed, the variable might have been renamedbaz
, and the user will not get much actionable intelligence out of the fact that ‘division by zero’ has occurred at some point, andbaz
was the culprit. Just test early for known incompatibilities, and stop further execution. The same goes, of course, for potentially malicious code.
In general, your code should be strict as to what it accepts, and you should not be afraid to reject anything that doesn’t look like what you’re looking for. Consider for this not only types but also values, e.g. if the value provided for a timeout in minutes is somewhere north of the lifetime of the universe, you should politely reject such an argument – with a good explanation, of course.
Update: After posting this on Reddit, u/BillWeld pointed out a great idiom for checking user inputs that’s most definitely worth reposting here:
f <- function(a, b, c) { if (getOption("warn") > 0) { stopifnot( is.numeric(a), is.vector(a), length(a) == 1, is.finite(a), a > 0, is.character(b), # Other requirements go here ) } # The main body of the function goes here }
I find this a great and elegant idiom, although it is your call, as the programmer, to decide which deviations and what degree of incompatibility should cause the function to fail as opposed to merely emit a warning.
THREE: Keep functions short and sweet.
Rule #4 of the Power of Ten states
No function should be longer than what can be printed on a single sheet of paper in a standard reference format with one line per statement and one line per declaration. Typically, this means no more than about 60 lines of code per function.
Rationale: Each function should be a logical unit in the code that is understandable and verifiable as a unit. It is much harder to understand a logical unit that spans multiple screens on a computer display or multiple pages when printed. Excessively long functions are often a sign of poorly structured code.
In practice, with larger screen sizes and higher resolutions, much more than a measly hundred lines fit on a single screen. However, since many users view R code in a quarter-screen window in RStudio, an appropriate figure would be about 60-80 lines. Note that this does not include comments and whitespaces, nor does it penalise indentation styles (functions, conditionals, etc.).
Functions should represent a logical unity. Therefore, if a function needs to be split for compliance with this rule, you should do so in a manner that creates logical units. Typically, one good way is to split functions by the object they act on.
FOUR: Refer to external functions explicitly.
In R, there are two ways to invoke a function, yet most people don’t tend to be aware of this. Even in many textbooks, the library(package)
function is treated as quintessentially analogous to, say, import
in Python. This is a fundamental misunderstanding.
In R, packages do not need to be imported in order to be able to invoke their functions, and that’s not what the library()
function does anyway. library()
attaches a package to the current namespace.
What does this mean? Consider the following example. The foreign
package is one of my favourite packages. In my day-to-day practice, I get data from all sorts of environments, and foreign
helps me import them. One of its functions, read.epiinfo()
, is particularly useful as it imports data from CDC’s free EpiInfo toolkit. Assuming that foreign
is in a library accessible to my instance of R,4, I can invoke the read.epiinfo()
function in two ways:
- I can directly invoke the function using its canonical name, of the form
package::function()
– in this case,foreign::read.epiinfo()
. - Alternatively, I can attach the entire
foreign
package to the namespace of the current session usinglibrary(foreign)
. This has three effects, of which the first tends to be well-known, the second less so and the third altogether ignored.- Functions in
foreign
will be directly available. Regardless of the fact that it came from a different package, you will be able to invoke it the same way you invoke, say, a function defined in the same script, by simply callingread.epiinfo()
. - If there was a package of identical name to any function in
foreign
, that function will be ‘shadowed’, i.e. removed from the namespace. The namespace will always refer to the most recent function, and the older function will only be available by explicit invocation. - When you invoke a function from the namespace, it will not be perfectly clear from a mere reading of the code what the function actually is, or where it comes from. Rather, the user or maintainer will have to guess what a given name will represent in the namespace at the time the code is running the particular line.
- Functions in
Controversially, my suggestion is
- to eschew the use of
library()
altogether, and - write always explicitly invoke functions outside those functions that are in the namespace at startup.
This is not common advice, and many will disagree. That’s fine. Not all code needs to be safety-critical, and importing ggplot2
with library()
for a simple plotting script is fine. But where you want code that’s easy to analyse, easy to read and can be reliably analysed as well, you want explicit invocations. Explicit invocations give you three main benefits:
- You will always know what code will be executed.
filter
may meandplyr::filter
,stats::filter
, and so on, whereas specifically invokingdplyr::filter
is unambiguous. You know what the code will be (simply invokingdplyr::filter
without braces or arguments returns the source), and you know what that code is going to do. - Your code will be more predictable. When someone – or something – analyses your code, they will not have to spend so much time trying to guess what at the time a particular identifier refers to within the namespace.
- There is no risk that as a ‘side effect’ various other functions you seek to rely on will be removed from the namespace. In interactive coding, R usually warns you and lists all shadowed functions upon importing functions with the same name into the namespace using
library()
, but for code intended to be bulk executed, this issue has caused a lot of headache.
Obviously, all of this applies to require()
as well, although on the whole the latter should not be applied in general.
FIVE: Don’t use require()
to import a package into the namespace.
Even seasoned R users sometimes forget the difference between library()
and require()
. The difference is quite simple: while both functions attempt to attach the package argument to the namespace,
require()
returnsFALSE
if the import failed, whilelibrary()
simply loads the package and raises an error if the import failed.
Just about the only legitimate use for require()
is writing an attach-or-install function. In any other case, as Yihui Xie points out, require()
is almost definitely the wrong function to use.
SIX: Aggressively manage package and version dependencies.
Packrat is one of those packages that have changed what R is like – for the better. Packrat gives every project a package library, akin to a private /lib/
folder. This is not the place to document the sheer awesomeness of Packrat – you can do so yourself by doing the walkthrough of Packrat. But seriously, use it. Your coworkers will love you for it.
Equally important is to make sure that you specify the version of R that your code is written against. This is best accomplished on a higher level of configuration, however.
SEVEN: Use a consistent style and automated code quality tools.
This should be obvious – we’re programmers, which means we’re constitutionally lazy. If it can be solved by code faster than manually, then code it is! Two tools help you in this are lintr
and styler
.
lintr
is an amazingly widely supported (from RStudio through vim to Sublime Text 3, I hear a version for microwave ovens is in the works!) linter for R code. Linters improve code quality primarily by enforcing good coding practices rather than good style. One big perk oflintr
is that it can be injected rather easily into the Travis CI workflow, which is a big deal for those who maintain multi-contributor projects and use Travis to keep the cats appropriately herded.styler
was initially designed to help code adhere to the Tidyverse Style Guide, which in my humble opinion is one of the best style guides that have ever existed for R. It can now take any custom style files and reformat your code, either as a function or straight from an RStudio add-in.
So use them.
EIGHT: Everything is a package.
Whether you’re writing R code for fun, profit, research or the creation of shareholder value, your coworkers and your clients – rightly! – expect a coherent piece of work product that has everything in one neat package, preferably version controlled. Sending around single R scripts might have been appropriate at some point in the mid-1990s, but it isn’t anymore. And so, your work product should always be structured like a package. As a minimum, this should include:
- A
DESCRIPTION
andNAMESPACE
file. - The source code, including comments.
- Where appropriate, data mappings and other ancillary data to implement the code. These go normally into the
data/
folder. Where these are large, such as massive shape files, you might consider using Git LFS. - Dependencies, preferably in a
packrat
repo. - The documentation, helping users to understand the code and in particular, if the code is to be part of a pipeline, explaining how to interact with the API it exposes.
- Where the work product is an analysis rather than a bit of code intended to carry out a task, the analysis as vignettes.
To understand the notion of analyses as packages, two outstanding posts by Robert M. Flight are worth reading: part 1 explains the ‘why’ and part 2 explains the ‘how’. Robert’s work is getting a little long in the tooth, and packages like knitr
have taken the place of vignettes as analytical outputs, but the principles remain the same. Inasmuch as it is possible, an analysis in R should be a self-contained package, with all the dependencies and data either linked or included. From the perspective of the user, all that should be left for them to do is to execute the analysis.
NINE: Power in names.
There are only two hard things in Computer Science: cache invalidation and naming things.
In general, R has a fair few idiosyncrasies in naming things. For starters, dots/periods .
are perfectly permitted in variable names (and thus function names), when in most languages, the dot operator is a binary operator retrieving the first operand object’s method called the second operand:
For instance, in Python, wallet.pay(arg1, arg2)
means ‘invoke the method pay
of the object wallet
with the arguments arg1
and arg2
‘. In R, on the other hand, it’s a character like any other, and therefore there is no special meaning attached to it – you can even have a variable contaning multiple dots, or in fact a variable whose name consists entirely of dots5 – in R, ..........
is a perfectly valid variable name. It is also a typcal example of the fact that justibecause you can do something doesn’t mean you also should do so.
A few straightforward rules for variable names in R are worth abiding by:
- Above all, be consistent. That’s more important than whatever you choose.
- Some style guides, including Google’s R style guide, treat variables, functions and constants as different entities in respect of naming. This is, in my not-so-humble opinion, a blatant misunderstanding of the fact that functions are variables of the type
function
, and not some distinct breed of animal. Therefore, I recommend using a unitary schema for all variables, callable or not. - In order of my preference, the following are legitimate options for naming:
- Underscore separated:
average_speed
- Dot separated:
average.speed
- JavaScript style lower-case CamelCase:
averageSpeed
- Underscore separated:
- Things that don’t belong into identifiers: hyphens, non-alphanumeric characters, emojis (??♂️) and other horrors.
- Where identifiers are hierarchical, it is better to start representing them as hierarchical objects rather than assigning them to different variables. For example, instead of
monthly_forecast_january
,monthly_forecast_february
and so on, it is better to have alist
associative array calledforecasts
in which the forecasts are keyed by month name, and can then be retrieved using the$key
or the[key]
accessors. If your naming has half a dozen components, maybe it’s time to think about structuring your data better.
Finally, in some cases, the same data may be represented by multiple formats – for instance, data about productivity is first imported as a text file, and then converted into a data frame. In such cases, Hungarian notation may be legitimate, e.g. txt_productivity
or productivity.txt
vs df_productivity
or productivity.df
. This is more or less the only case in which Hungarian notation is appropriate.6
And while we’re at variables: never, ever, ever use =
to assign. Every time you do it, a kitten dies of sadness.
For file naming, some sensible rules have served me well, and will be hopefully equally useful for you:
- File names should be descriptive, but no longer than 63 characters.
- File names should be all lower case, separated by underscores, and end in
.R
. That’s a capital R. Not a lower-case R. EveR. - Where there is a ‘head’ script that sequentially invokes (sources) a number of subsidiary scripts, it is common for the head script to be called
00-.R
, and the rest given a sequential corresponding to the order in which they are sourced and a descriptive name, e.g.01-load_data_from_db.R
,02-transform_data_and_anonymise_records.R
and so on. - Where there is a core script, but it does not invoke other files sequentially, it is common for the core script to be called
00-base.R
ormain.R
. As long as it’s somewhere made clear to the user which file to execute, all is fair. - The injunction against emojis and other nonsense holds for file names, too.
TEN: Know the rules and their rationale, so that you know when to break them.
It’s important to understand why style rules and defensive programming principles exist. How else would we know which rules we can break, and when?
The reality is that there are no rules, in any field, that do not ever permit of exceptions. And defensive programming rules are no exception. Rules are tools that help us get our work done better and more reliably, not some abstract holy scripture. With that in mind, when can you ignore these rules?
- You can, of course, always ignore these rules if you’re working on your own, and most of your work is interactive. You’re going to screw yourself over, but that’s your right and privilege.
- Adhering to common standards is more important than doing what some dude on the internet (i.e. my good self) thinks is good R coding practice. Coherence and consistency are crucial, and you’ll have to stick to your team’s style over your own ideas. You can propose to change those rules, you can suggest that they be altogether redrafted, and link them this page. But don’t go out and start following a style of your own just because you think it’s better (even if you’re right).
- It’s always a good idea to appoint a suitable individual – with lots of experience and little ego, ideally! – as code quality standards coordinator (CQSC). They will then centrally coordinate adherence to standards, train on defensive coding practices, review operational adherence, manage tools and configurations and onboard new people.
- Equally, having an ‘editor settings repo’ is pretty useful. This should support, at the very least, RStudio
lintr
andstyler
. - Some prefer to have the style guide as a GitHub or Confluence wiki – I generally advise against that, as that cannot be tracked and versioned as well as, say, a bunch of RST files that are collated together using Sphinx, or some RMarkdown files that are rendered automatically upon update using a GitHub webhook.
Conclusion
A few years ago, at a seminar on coding to FDA CDRH standards, the instructor finished by giving us his overriding rule: in the end, always code as if your life, or that of your loved ones, depended on the code you write (because it very well may someday!). This may sound dramatic in the context of R, which is primarily a statistical programming language, but the point stands: code has real-life consequences, and we owe it to those whose lives, careers or livelihoods depend on our code to give them the kind of code that we wish to rely on: well-tested, reliable and stable.
References
1. | ↑ | One crucial element here: keep in mind the order of parameters – because the explicit should override the implied, your code should look at the arguments first, then the environment variables, then the configuration file! |
2. | ↑ | Eagle-eyed readers might spot the mutation in the example. This is indeed the T310C mutation on the TNFRSF13B gene (17p11.2), which causes autosomal dominant type 2 Common Variable Immune Deficiency, a condition I have, but manage through regular IVIG, prophylactic antibiotics and aggressive monitoring. |
3. | ↑ | Holzmann, G.J. (2006). The Power of 10: Rules for developing safety-critical code. IEEE Computer 39(6):95-99. |
4. | ↑ | R stores packages in libraries, which are basically folders where the packages reside. There are global packages as well as user-specific packages. For a useful overview of packages and package installation strategies, read this summary by Nathan Stephens. |
5. | ↑ | The exception is ... , which is not a valid variable name as it collides with the splat operator. |
6. | ↑ | In fact, the necessity of even this case is quite arguable. A much better practice would be simply importing the text as productivity , then transform it into a data frame, if there’s no need for both versions to continue coexisting. |
The post The Ten Rules of Defensive Programming in R appeared first on Doodling in Data.
R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.