Keep if clauses side-effect free
Avoid writing if clauses that have side effects. The purpose of an if statement is to determine whether a condition is true, not to execute code as a side effect of the test. When using the return value directly in an if statement, its meaning may become unclear. For example, the method enqueueMessage() could return true if the message was enqueued or true if the queue is full.
To make the code more readable, make the return value explicit using a variable. Methods that don't have side effects should have names that clearly indicate this, such as isEmpty(). Calling methods with side effects in if statements can make the code difficult to understand. If a reader skim-reading the code, they may not notice the call to a method with side effects.
Consider the following code from production: It was unclear where items were being added to the set. The code read as if the if statement had no side effects. However, the add() method was called, and it was unclear what this did. The Javadoc for the Set class states that the add() method returns true if the set did not already contain the specified element.
The code also uses extra convoluted logic due to the continue keyword. A more straightforward approach would be to use a variable to make the return value explicit. This would make the code more readable and avoid confusion. Be cautious when using methods with side effects in if statements. It's important to understand that short-circuit evaluation, while useful, should not be used to avoid calling methods with side effects.
If statements were created to handle these situations and should be used accordingly. Writing the code in a more explicit and straightforward manner may seem like an extra step, but it can save time and effort in the long run by making the code easier to follow for future readers.
Written by urgent.news from Lobsters's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.