30 Side-effect soup

Side-effect soup occurs when you mix side-effects and regular computation within the same function.

30.1 What is a side-effect?

There are two main types of side-effect:

  • those that give feedback to the user.
  • those that change some global state.

30.1.1 User feedback

  • Signalling a condition, with message(), warning(), or stop().

  • Printing to the console with cat().

  • Drawing to the current graphics device with base graphics or grid.

30.1.2 Global state

  • Creating (or modifying) an existing binding with <-.

  • Modifying the search path by attaching a package with library().

  • Changing the working directory with setwd().

  • Modifying a file on disk with (e.g.) write.csv().

  • Changing a global option with options() or a base graphics parameter with gpar().

  • Setting the random seed with set.seed()

  • Installing a package.

  • Changing environment variables with Sys.setenv(), or indirectly via a function like Sys.setlocale().

  • Modifying a variable in an enclosing environment with assign() or <<-.

  • Modifying an object with reference semantics (like R6 or data.table).

More esoteric side-effects include:

  • Detaching a package from the search path with detach().

  • Changing the library path, where R looks for packages, with .libPaths()

  • Changing the active graphics device with (e.g.) png() or dev.off().

  • Registering an S4 class, method, or generic with methods::setGeneric().

  • Modifying the internal .Random.seed

30.3 Why is it bad?

Side-effect soup is bad because:

  • If a function does some computation and has side-effects, it can be challenging to extract the results of computation.

  • Makes code harder to analyse because it may have non-local effects. Take this code:

    If compute() or calculate() don’t have side-effects then you can predict what df will be. But if compute() did options(stringsAsFactors = FALSE) then df would now contain a character vector rather than a factor.

Side-effect soup increases the cognitive load of a function so should be used deliberately, and you should be especially cautious when combining them with other techniques that increase cognitive load like tidy-evaluation and type-instability.

30.4 How avoid it?

30.4.1 Localise side-effects

Constrain the side-effects to as small a scope as possible, and clean up automatically to avoid side-effects. withr

30.4.2 Extract side-effects

It’s not side-effects that are bad, so much as mixing them with non-side-effect code.

Put them in a function that is specifically focussed on the side-effect.

If your function is called primarily for its side-effects, it should return the primary data structure (which should be first argument), invisibly. This allows you to call it mid-pipe for its side-effects while allow the primary data to continue flowing through the pipe.

30.4.3 Make side-effects noisy

Primary purpose of the entire package is side-effects: modifying files on disk to support package and project development. usethis functions are also designed to be noisy: as well as doing it’s job, each usethis function tells you what it’s doing.

But some usethis functions are building blocks for other more complex tasks.

30.4.4 Provide an argument to suppress

You’ve probably used base::hist() for it’s side-effect of drawing a histogram:

But you might not know that hist() also returns the result of the computation. If you call plot = FALSE it will simply return the results of the computation:

This is a good approach for retro-fitting older functions while making minimal API changes. However, I think it dilutes a function to be both used for plotting and for computing so should be best avoided in newer code.

30.4.5 Use the print() method

An alternative approach would be to always return the computation, and instead perform the output in the print() method.

Of course ggplot2 isn’t perfect: it creates an object that specifies the plot, but there’s no easy way to extract the underlying computation so if you’ve used geom_smooth() to add lines of best fit, there’s no way to extract the values. Again, you can see the results, but you can’t touch them, which is very frustrating!

30.4.6 Make easy to undo

If all of the above techniques fail, you should at least make the side-effect easy to undo. A use technique to do this is to make sure that the function returns the previous values, and that it can take it’s own input.

This is how options() and par() work. You obviously can’t eliminate those functions because their complete purpose is have global changes! But they are designed in such away that you can easily undo their operation, making it possible to apply on a local basis.

There are two key ideas that make these functions easy to undo:

  1. They invisibly return the previous values as a list:

  2. Instead of n named arguments, they can take a single named list:

    (I wouldn’t recommend copying this technique, but I’d instead recommend always taking a single named list. This makes the function because it has a single way to call it and makes it easy to extend the API in the future, as discussed in Chapter 19)

Together, this means that you easily can set options temporarily.:

If temporarily setting options in a function, you should always restore the previous values using on.exit(): this ensures that the code is run regardless of how the function exits.

30.5 Package considerations

Code in package is executed at build-time.i.e. if you have:

For mac and windows, this will record when CRAN built the binary. For linux, when the package was installed.

Beware copying functions from other packages:

Version of barfy might be different between run-time and build-time.

Introduces a build-time dependency.

https://github.com/r-lib/devtools/issues/1788