Every branch of an if-else or conditional expression is the same
What it finds
if (c) { f(); } else { f(); }: when every branch of an if does the same, the condition decides nothing. Usually one branch was copied and not changed. The same goes for a conditional expression whose two outcomes are the same, as c ? x : x.
A chain of else if branches is reported only when it ends in a plain else and every branch is the same: giving each case its own branch even where two do the same is a common way to list the cases. Empty blocks are left alone, and so are switches whose cases all do the same, a common placeholder for cases still to come.
Some branches are the same on purpose. Conditions with instanceof are left alone, since a pattern variable can give the same name a different meaning in each branch, as are conditions that are a constant flag such as DEBUG, whose branches are kept apart for builds that change it, and conditional expressions whose outcomes are literals. Others are kept apart with a comment that says why, often a note that one branch is still to be done, which is why the rule is not in the default tier.
From the rule's source, identical_branches.rs.
import java.util.List; class Branches { static final boolean DEBUG = false; int f(boolean ok, int n, List<Integer> items, Object value) { if (ok) {tx0 reports: both branches of this if do the same n = g(n); } else { n = g(n); } if (n > 1) {tx0 reports: every branch of this if chain does the same items.add(n); } else if (n > 0) { items.add(n); } else { items.add(n); } if (ok) n++; else n++;tx0 reports: both branches if (n > 1) { items.add(n); } else if (n > 0) { items.add(n); } if (n > 1) { items.add(n); } else if (n > 0) { items.add(n); } else { items.add(1); } if (ok) { } else { } int a = ok ? items.get(n) : items.get(n);tx0 reports: both outcomes of this conditional expression are items.get(n) int b = ok ? n : n + 1; int c = ok ? 0 : 0; if (value instanceof String s) { n = value.hashCode(); } else { n = value.hashCode(); } if (DEBUG) { n = g(n); } else { n = g(n); } switch (n) { case 1: n = g(n); break; default: n = g(n); break; } return a + b + c + n; } int g(int n) { return n; }} Turn it on, off or suppress it
The rule runs from the recommended tier up. To turn it on in a lower tier, give it a level in tx0.toml:
[rules]
"tx0/java:identical-branches" = "warning"To keep one finding, suppress it with a reason. tx0 suppress ID --reason "..." writes the comment on the line before the code:
// tx0: ignore[tx0/java:identical-branches] reason="..."tx0 explain tx0/java:identical-branches shows the same in the terminal. Found a false positive? Report it.