Long winding if conditions should be avoided if at all possible, yet sometimes w
ID: 639295 • Letter: L
Question
Long winding if conditions should be avoided if at all possible, yet sometimes we all end up writing them. Even if it's a very simple condition, the involved statements are sometimes simply very wordy, so the whole condition ends up being very lengthy. What's the most readable way to format those?
if (FoobarBaz::quxQuux(corge, grault) || !garply(waldo) || fred(plugh) !== xyzzy) {
thud();
}
or
if (
FoobarBaz::quxQuux(corge, grault)
|| !garply(waldo)
|| fred(plugh) !== xyzzy
) {
thud();
}
or
if (FoobarBaz::quxQuux(corge, grault)
|| !garply(waldo)
|| fred(plugh) !== xyzzy) {
thud();
}
or
thudable = FoobarBaz::quxQuux(corge, grault);
thudable ||= !garply(waldo);
thudable ||= fred(plugh) !== xyzzy;
if (thudable) {
thud();
}
or any other preferences?
Explanation / Answer
Often, a long if condition is the sign of code that needs refactoring, but sometimes you can't avoid it. In those cases, I prefer the first:
if (bar || baz || quux) { ... }
Because you're able to tell what's going on with one line. However, I'd much rather do something like this, when possible:
function foo() {
return bar || baz || quux;
}
if (foo()) { ... }
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.