13 Avoid magical defaults

13.1 What’s the problem?

If a function behaves differently when the default value is suppled explicitly, we say it has a magical default. Magical defaults are best avoided because they make it harder to interpret the function specification.

13.2 What are some examples?

13.3 What are the exceptions?

It’s ok to use this behaviour when you want the default value of one argument to be the same as another. For example, take rlang::set_names(), which allows you to create a named vector from two inputs:

The default value for the names is the vector itself. This provides a convenient shortcut for naming a vector with itself:

You can see this same technique in merge(), where all.x and all.y default to the same value as all, and in factor() where labels defaults to the same value as levels.

If you use this technique, make sure that you never use the value of an argument that comes later in the argument list. For example, in file.copy() overwrite defaults to the same value as recursive, but the recursive argument is defined after overwrite:

This makes the defaults arguments harder to understand because you can’t just read from left-to-right.

13.4 What causes the problem?

There are three primary causes:

13.5 How do I remediate the problem?

This problem is generally easy to avoid for new functions:

  • Don’t use default values that depend on variables defined inside the function.

  • Don’t use missing()4.

  • Don’t use unexported functions.

If you have a made a mistake in an older function you can remediate it by using a NULL default, as described in Chapter 14. If the problem is caused by an unexported function, you can also choose to document and export it.

This modification should not break existing code, because expands the function interface: all previous code will continue to work, and the function will also work if the argument is passed NULL input (which probably didn’t previously).

For functions like data.frame() where NULL is already a permissible value, you’ll need to use a sentinel object, as described in Section 14.4.3.

  1. The only exceptions are described in Sections 10.3.1 and 10.3.2.