Infinite loops can have harmful consequences, such as blocking the browser tab, making a server unresponsive or consuming a huge amount of resources.
When writing a loop, make sure that it's obvious the loop terminates.
A sentinel value is a value such as
-1 or the empty string, that has a special
meaning in the context of a program.
Sentinel values are undesirable because:
It isn't obvious that a type contains a sentinel value, which may result in new code not handling the sentinel value without getting a compiler error or looking obviously wrong.
Mistakes or future changes may result in sentinel values colliding with real values.
A better option is to use an adequate composite type such as a union type.
When a piece of code contains an
if condition, the code can take 2 paths. If
the piece of code contains two nested
if conditions, the code can take 4. If
there are three the code can take 8 paths.
Each of these paths can hide a bug. The fewer conditionals there are, the fewer edge cases there are, and the more likely it is to come across the bugs when testing.
It's usually better to write code in the simplest way possible. However, you might have to write code that looks unnecessarily complicated, for example to improve performance or work around problems in your environment.
If the developers who read your code don't understand why it is written the way it is, they may rewrite it the straightforward way, potentially causing bugs, performance regressions or other problems.
You can explain why your code is written the way it is in comments, commit messages, or, even better, unit tests that test the behavior that is unique to your code.