3 ms·
In general you're right but I think for the specific pattern of checking preconditions and handling errors the author is right. if file_exists(path) {
by Spivak 6y ago
In general you're right but I think for the specific pattern of checking preconditions and handling errors the author is right.
if file_exists(path) {
# use path ...
db = get_conn()
if db.is_connected() {
# use db ...
} else {
ret = new Error("db")
}
} else {
ret = new Error("path")
}
return ret
Every check we need to do increases our nesting and makes it look like it's got lots of different paths when really it has exactly one happy path and many error paths.
if ! file_exists(path) [
return new Error("path")
}
# use path ...
db = get_conn()
if ! db.is_connected() {
return new Error("db")
}
# use db ...
This is exactly my rule -- only if/else if it's the happy path that's branching.
- 100011_100001 6y agoThat's a fair rebuttal. Depending on the situation though 'if not this - throw error' can be mitigated. It's one of the reasons why I try to avoid nulls coming into the code, otherwise you have to null check everywhere.