Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

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()) { ... }

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote