Value converted to text by concatenating an empty string
ID |
apex.maintainability.string_concat_for_conversion |
Severity |
info |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Readability |
Language |
Apex |
Description
Reports a conversion written as '' + value or value + '', where the empty literal exists only to turn the value into text.
Rationale
The empty literal is a side effect being used as an API: nothing in '' + amount says "convert", so a reader has to infer the intent, and the next editor can delete the literal while tidying a concatenation and change the expression’s type. String.valueOf(amount) says what is happening, and for a Decimal or a Datetime it is also the place where an explicit format can be applied later.
The following code illustrates the pattern detected by this rule:
public class StringConcatConversion {
public String describe(Decimal amount, Integer count, String name) {
// FLAGGED: Value converted to text by concatenating an empty string
String a = '' + amount;
// FLAGGED: Value converted to text by concatenating an empty string
String b = count + '';
System.debug(a + b);
String c = String.valueOf(amount);
String d = 'Total: ' + amount;
String e = name + ' (' + count + ')';
return c + d + e;
}
}