design icon indicating copy to clipboard operation
design copied to clipboard

Early exits

Open hadley opened this issue 4 years ago • 2 comments

If you have an if statement with a large if and small else:

if (cond) {
  # 
  # 
  # 
  # 
  # 
  # 
  # 
  # 
} else {
  something()
}

It's worth considering flipping the order and using an early exit:

if (!cond) {
  return(something())
}

# 
#

hadley avatar Feb 02 '21 19:02 hadley

Example from dbplyr:

check_groups <- function(.groups) {
  if (!is_null(.groups) && !.groups %in% c("drop_last", "drop", "keep")) {
    abort(c(
      paste0(
        "`.groups` can't be ", as_label(.groups),
        if (.groups == "rowwise") " for lazy tables"
      ),
      i = 'Possible values are NULL (default), "drop_last", "drop", and "keep"'
    ))
  }
}

to


check_groups <- function(.groups) {
  if (is_null(.groups)) {
    return()
  }

  if (.groups %in% c("drop_last", "drop", "keep")) {
    return()
  }

  abort(c(
    paste0(
      "`.groups` can't be ", as_label(.groups),
      if (.groups == "rowwise") " in dbplyr"
    ),
    i = 'Possible values are NULL (default), "drop_last", "drop", and "keep"'
  ))
}

hadley avatar Feb 03 '21 13:02 hadley

Some more stuff at https://www.geepawhill.org/2019/03/03/refactoring-pro-tip-easiest-nearest-owwie-first/

hadley avatar Oct 01 '21 03:10 hadley