Ternary Expression With Negated Condition

ID

java.ternary_with_negation

Severity

info

Remediation Complexity

medium

Remediation Risk

low

Remediation Effort

medium

Resource

Code Smell

Language

Java

Tags

best-practice, code-style

Description

Reports ternary conditional expressions where the condition is a logical negation (!expr ? a : b). Such expressions are harder to read because the reader must mentally invert the condition to understand which branch executes when. Swapping the branches and removing the negation makes the intent clearer.

Rationale

A negated ternary condition adds an unnecessary cognitive step for the reader. The double reversal (negation in the condition, then choosing the "true" branch) is confusing, especially in longer expressions. Positive conditions are easier to reason about.

// Bad -- negated condition
String result = !isValid ? "invalid" : "valid";
int sign = !(x > 0) ? -1 : 1;

Remediation

Remove the negation and swap the true and false branches.

// Good -- positive condition with swapped branches
String result = isValid ? "valid" : "invalid";
int sign = (x > 0) ? 1 : -1;