Use template strings rather than string concatenation for dynamic formulas
Why is this an issue?
When building dynamic formulas in Apex, using template mode with merge field syntax is easier to read and maintain than traditional string concatenation:
Readability: Template syntax resembles actual formula syntax.
Maintainability: Changes are easier to make and review.
Error reduction: Less chance of concatenation mistakes.
Examples
Example of incorrect code:
// String concatenation - hard to read
String formula = 'IF(' + fieldName + ' > ' + threshold + ', ' +
'"High", ' +
'IF(' + fieldName + ' > ' + lowThreshold + ', ' +
'"Medium", "Low"))';
FormulaEval.FormulaInstance formulaInstance =
FormulaEval.FormulaBuilder.builder()
.withFormula(formula)
.withReturnType(FormulaEval.FormulaReturnType.STRING)
.build();
Example of correct code:
// Template mode - cleaner and clearer
String formulaTemplate = 'IF({!fieldName} > {!threshold}, "High", ' +
'IF({!fieldName} > {!lowThreshold}, "Medium", "Low"))';
FormulaEval.FormulaInstance formulaInstance =
FormulaEval.FormulaBuilder.builder()
.withFormula(formulaTemplate)
.withReturnType(FormulaEval.FormulaReturnType.STRING)
.parseAsTemplate(true) // Enable template mode
.build();
How can I fix violations?
Use merge field syntax: Replace concatenated variables with
{!variableName}.Enable template mode: Call
.parseAsTemplate(true)on the formula builder.Refactor formulas: Update existing formulas to use the cleaner syntax.
When should I disable this rule?
You may dismiss specific violations for simple formulas where concatenation is sufficiently clear.
Resources
