if and else run the same single statement
ID |
apex.correctness.identical_branches |
Severity |
high |
Remediation Complexity |
medium |
Remediation Risk |
medium |
Remediation Effort |
low |
Resource |
Control Flow |
Language |
Apex |
Description
Reports an if / else whose two branches are the same single statement, so the condition changes nothing. Only the single-statement form of each branch is reported.
Rationale
The condition is evaluated, both answers lead to the same work, and the branch exists only to suggest that something differs. Either the condition is redundant and the reader is being told about a decision that is not made, or - far more often - one of the two statements was meant to differ and was copied without being edited: the other status value, the other field, the other multiplier. In that second case the record is written with the wrong value for one half of the inputs, and nothing fails, because the code does exactly what it says.
The following code illustrates the pattern detected by this rule:
public class InvoicePoster {
public static void post(Invoice__c inv, Boolean express) {
// FLAGGED: if and else run the same single statement
if (express) {
inv.Status__c = 'Posted';
} else {
inv.Status__c = 'Posted';
}
update inv;
}
public static Decimal fee(Decimal amount, Boolean member) {
// FLAGGED: if and else run the same single statement
if (member) {
return amount * 0.02;
} else {
return amount * 0.02;
}
}
public static Decimal feeFixed(Decimal amount, Boolean member) {
if (member) {
return amount * 0.01;
} else {
return amount * 0.02;
}
}
public static void postFixed(Invoice__c inv, Boolean express) {
if (express) {
inv.Status__c = 'Posted';
}
update inv;
}
public static void stamp(Invoice__c inv, Boolean express) {
if (express) {
inv.Status__c = 'Posted';
} else {
inv.Description__c = 'Posted';
}
update inv;
}
}