tidyverse / design

Tidyverse design principles
https://design.tidyverse.org
Other
217 stars 51 forks source link

Early exits #124

Open hadley opened 3 years ago

hadley commented 3 years ago

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 commented 3 years ago

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 commented 2 years ago

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