String.isEmpty used where whitespace also counts as empty
ID |
apex.correctness.string_isempty_instead_of_isblank |
Severity |
high |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Api Usage |
Language |
Apex |
Description
Reports a call to String.isEmpty or String.isNotEmpty, which treat a string of spaces as non-empty, where String.isBlank and String.isNotBlank are usually what is meant.
Rationale
A value that arrives from a form, an integration payload or a CSV import frequently holds a space or a non-breaking space rather than nothing at all. String.isEmpty(' ') is false, so the guard passes and the blank value flows on - into a required field, a key used for matching, or a message shown to a user. The defect is invisible in tests, because test data is written with clean literals.
The following code illustrates the pattern detected by this rule:
public class BlankChecks {
public void validate(Account a) {
// FLAGGED: String.isEmpty used where whitespace also counts as empty
if (String.isEmpty(a.Name)) {
a.addError(Label.Account_Name_Required);
}
// FLAGGED: String.isEmpty used where whitespace also counts as empty
if (String.isNotEmpty(a.Description)) {
System.debug(a.Description);
}
if (String.isBlank(a.Name)) {
a.addError(Label.Account_Name_Required);
}
if (String.isNotBlank(a.Description)) {
System.debug(a.Description);
}
}
}