BSL202 — Incorrect use of "StrTemplate"¶
Summary¶
Incorrect use of "StrTemplate"
Identifiers¶
| Field | Value |
|---|---|
| Rule code | BSL202 |
| Compatible alias | IncorrectUseOfStrTemplate |
| Severity | ERROR |
| Enabled by default | Yes |
| Implemented | Yes |
| Tags | correctness |
Behavior¶
- The public identifier
BSL202and aliasIncorrectUseOfStrTemplateare stable. - The rule reports the cases documented on this page.
- Suppressions and project configuration are applied before publication.
- The rule requires neither an external analyzer nor network access.
Configuration and suppression¶
BSL### is the primary stable identifier. The compatible alias is accepted
in select, ignore, and compatible block suppression comments.
All three suppression families support both a current line and a range. When an opening comment follows code, it affects only that line. Use any one form:
noqa:
bsl-disable:
- compatible
BSLLSform:
When the same opening comment is on a line by itself, it starts a range. Close it with the matching marker from the same family:
// noqa: BSL202
// code without this diagnostic
// noqa-enable: BSL202
// bsl-disable: BSL202
// code without this diagnostic
// bsl-enable: BSL202
// BSLLS:IncorrectUseOfStrTemplate-off
// code without this diagnostic
// BSLLS:IncorrectUseOfStrTemplate-on
To disable the rule until the end of the file, omit the closing
noqa-enable, bsl-enable, or BSLLS:…-on marker.
Opening and closing markers must belong to the same family.
Description¶
When using the StrTemplate method, you must carefully compose the template string and pass the correct number of parameters. So, it is quite easy to make mistakes when passing values for StrTemplate.
It is important to remember that
- StrTemplate only accepts parameters from %1 to %10
- if you want to pass a number immediately after the template, you need to add parentheses - "%(1)45"
Examples¶
Option 1 - the number of values passed after the template string is not equal (less or more) to the maximum number from a string like %N inside the template string
StrTemplate("Name (version %1)"); // not passed required parameter for %1StrTemplate("%1 (version %2)", Name); // not passed required parameter for %2
Option 2 - no values are passed at all, except for a formatted string due to the large number of parentheses inside a simple expression with NStr and StrTemplate:
StrTemplate(NStr("en='Name (version %1)'", Version()));
Here mistake not closed parenthesis for NStr. As a result, the expression after evaluating NStr becomes empty.
It is rather difficult to detect such an error by reading the code due to the presence of parentheses. And you can only catch it at runtime by getting an exception.
Correct option
- StrTemplate(NStr("en='Name (version %1)'"), Version());
Option 3 - correct example of passing digits immediately after a template value
- StrTemplate("Name %(1)2"), Name); // if pass the value "MyString", then the result will be "MyString2"