design
design copied to clipboard
Early exits
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())
}
#
#
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"'
))
}
Some more stuff at https://www.geepawhill.org/2019/03/03/refactoring-pro-tip-easiest-nearest-owwie-first/