Inverted boolean logic is hard to read and should be avoided

This product is not supported for your selected Datadog site. ().

Metadata

ID: apex-code-style/inverted-boolean-logic

Language: Apex

Severity: Notice

Category: Best Practices

Description

This rule highlights the importance of avoiding inverted boolean logic, such as using negations with equality or relational expressions. Inverted boolean logic often makes code harder to read and understand because it requires extra mental effort to parse expressions like !(foo == 42) instead of the more straightforward foo != 42. Clear and direct boolean expressions improve code readability and maintainability.

To comply with this rule, prefer writing boolean expressions without negations around comparisons. For example, use foo != 42 instead of !(foo == 42), and bar <= 51 instead of !(bar > 51). Adopting this practice leads to cleaner, more intuitive code that aligns with common coding standards and best practices in Apex development.

Non-Compliant Code Examples

if (!(foo == 42)) {
}


Boolean b = !(bar > 51);

Compliant Code Examples

if (foo != 42) {
}


Boolean b = (bar <= 51);
https://static.datadoghq.com/static/images/logos/github_avatar.svg https://static.datadoghq.com/static/images/logos/vscode_avatar.svg jetbrains

Seamless integrations. Try Datadog Code Security