What is the best practice for checking multiple conditions, in no particular order?
The example in question needs to check four distinct conditions, in any order, and fail showing the correct error message.
The examples below use a C-like syntax.
Option 1: Check all at once
This method isn't preferred because the reasons why the condition failed aren't easy to discern.
if (A && B && C && D) {
// continue here...
} else {
return "A, B, C, or D failed";
}
Option 2: Nested Conditions
In the past, I used to use nested conditional statements, like so. This can get really confusing.
if (A) {
if (B) {
if (C) {
if (D) {
// continue here...
} else {
return "D failed"
}
} else {
return "C failed";
}
} else {
return "B failed";
}
} else {
return "A failed";
}
Option 3: Fail-early
This is the current method I use, which I like to call fail-early. As soon as a "bad" condition is hit, it returns.
if (!A) {
return "A failed";
}
if (!B) {
return "B failed";
}
if (!B) {
return "C failed";
}
if (!D) {
return "D failed";
}
// continue here...
Option 4: Collect Errors
One last approach I can think of is a sort of collection of errors. If the conditions to test for are completely separate, one might want to use this approach.
String errors = "";
if (!A) {
errors += "A failed\n";
}
if (!B) {
errors += "B failed\n";
}
if (!C) {
errors += "C failed\n";
}
if (!D) {
errors += "D failed\n";
}
if (errors.isEmpty()) {
// continue here...
} else {
return errors;
}
What are the best practices for checking multiple conditions? In terms of expectations, it ideally behaves like example 4, where details of all the failures are returned.