stop() / return() Early for Shorter Code

1 · Yihui Xie · Jan. 2, 2018, midnight
One little interesting programming habit I developed a few years ago was to stop() or return() as early as possible in a function. The main reason for this is to reduce the number of lines of code and white spaces for indentation. A few quick examples (for illustration purposes only): sqrt2 = function(x) { if (x >= 0) { sqrt(x) } else { stop("x must be non-negative") } } I’d stop early to reduce the number of lines of code from 7 to 6, and save 8 spaces: sqrt2 = function(x) { if...