New rule idea: Prefer .Substring() over CopyStr() #272
Arthurvdv
started this conversation in
Suggestions
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
Proposal
A new analyzer rule that suggests replacing
CopyStr(text, startIndex, length)withtext.Substring(startIndex, length)when the project'sapp.jsonhas an"application"version of"27.1.0.0"or higher.Why?
Cross-language familiarity.
.Substring()is the standard method name in C#, Java, JavaScript, Python, and most other languages.CopyStris a BC/NAV-specific built-in that developers coming from other ecosystems won't recognize.Fluent, object-oriented style. Calling
.Substring()directly on the text variable reads naturally left-to-right (MyText.Substring(1, 5)) instead of wrapping it in a function (CopyStr(MyText, 1, 5)). This improves code readability and makes intent clearer.AI-assisted development. AI coding tools (Copilot, ChatGPT, etc.) are trained predominantly on mainstream language patterns. They are far more likely to suggest and correctly reason about
.Substring()than the BC-specificCopyStr. Using the common method name reduces friction when working with AI assistants.Discoverability. New AL developers can look up
.Substring()behavior based on general programming knowledge, whereasCopyStrrequires BC-specific documentation.Prerequisites
This rule should only fire when the
"application"property inapp.jsonis"27.1.0.0"or higher. The runtime error that previously made.Substring()unsafe (when length exceeds the string) was fixed in BC 27.0 platform (online) and guaranteed in BC 27.1 (all deployment types). The"runtime"property and AL Language version are not relevant here, only the application version matters.Current state in ALCops
Analyzer: PC0022 (PossibleOverflowAssigning) already handles both
The analyzer already recognizes both
CopyStrandSubstringwhen calculating result lengths. No changes needed on the diagnostic side.CodeFix:
PossibleOverflowAssigningApplyCopyStrneeds an updateThe code fix for PC0022 currently always wraps with
CopyStr, generating code like:When the app targets application
27.1.0.0or higher, the code fix should instead generate:This makes the generated code consistent with modern AL style and avoids the
Text.static class prefix.TODO
PossibleOverflowAssigningApplyCopyStrcode fix to emit.Substring()when app.json application >= 27.1.0.0HasFixSubstring/test fixture variants alongside existingHasFixCopyStr/Reference
Blog post by Natalie Karolak explaining the change and when it is safe to use:
https://nataliekarolak.wordpress.com/2026/04/23/using-substring-to-replace-copystr/
Beta Was this translation helpful? Give feedback.
All reactions