I think the following while (true) shouldn't be flagged by literal_only_boolean_expressions :
/// Return an unused TCP port number.
Future<int> findAvailablePort() async {
int port = 20000;
while (true) { // LINT
try {
ServerSocket socket =
await ServerSocket.bind(InternetAddress.LOOPBACK_IP_V4, port);
await socket.close();
return port;
} catch (_) {
port++;
}
}
}
Perhaps it'd be worth to create another rule to ensure the loop can be exited (by a break, return, throw, rethrow...)
+1 to the original post.
the justification here for the current lint rule includes flawed logic. it says,
"If the condition cannot evaluate to anything but true, the conditional statement is completely redundant."
no, not in the case of while (true) and do while (true).
i can't think of any other case, so it seems reasonable to make this into a special case for this lint rule.
perhaps the topic of the 2nd post should go into its own issue.
See also https://github.com/dart-lang/sdk/issues/34181#issuecomment-414125985
(For the for loop, omitting the condition is the traditional way to make an infinite loop, not writing
true).
I lean towards the simple solution, allowing while(true) and the related for loop. Would love to hear any reservations though.
/cc @bwilkerson
The while and do loops seem like reasonable exceptions, but I've also always seen the condition omitted from a for loop, so I'm hesitant to encourage that case.
At a minimum, we should add an "Good" example of using for (;;) instead of while (true)
FWIW, preferring for (;;) seems backward to me. When the loop condition is some non-constant expression, I generally use for for definite loops and while for indefinite ones. (Stealing something that munificent wrote (and taking it out of context): "for loops are implicitly terminated".)
Situations where I'd want an "infinite" loop are invariably indefinite cases.
The more I think about this lint, the less value I see in it. I have a hard time imagining myself or others unintentionally writing conditions comprised of only literals, especially the examples from the literal_only_boolean_expressions documentation. Was that really a big enough problem to warrant adding the lint? As noted in https://github.com/dart-lang/sdk/issues/34181#issue-351775732, enabling this lint reported only false positives when tried against the Flutter repo.
In contrast, there are a few cases where I intentionally write such conditions:
while (true) { ... }if (false) { ... } to temporarily disable some code during development/testing/debugging. Or similarly, modifying an existing if (someBooleanExpression) check to if (true || ...) or if (false && ...) to temporarily force going down a particular path.