An issue is raised when a conditional expression (with a condition determining which of two alternative expressions to evaluate) performs the same operation on both branches, differing only in the arguments.
In Java, this refers to the ternary operator with the syntax condition ? trueExpr : falseExpr.
When both branches of a ternary operator apply the same function call or operation to different values, the code contains unnecessary duplication. This pattern makes the code harder to read because the common operation is stated twice instead of once.
Consider this example:
message = isError ? formatMessage(errorText) : formatMessage(warningText)
Here, the message formatting function appears in both branches. This duplication obscures the actual difference between the branches (the input value) and makes the code longer than necessary.
By moving the condition inside the function call, you highlight what actually varies:
message = formatMessage(isError ? errorText : warningText)
This refactored version:
This pattern applies to function calls, object creation, array access, and other operations that are identical in both branches.
This issue has a minor impact on code maintainability:
Move the ternary operator inside the common method call or operation. The condition should determine which argument is passed, not which method is called.
String result = condition ? foo(a) : foo(b); // Noncompliant
String result = foo(condition ? a : b);