Credence.Rule.NoStringLengthForCharCheck
(credence v0.3.2)
Copy Markdown
Performance rule: Detects String.length(x) == 1 (or != 1) used to
validate that a string is a single character.
String.length/1 traverses the entire string to count grapheme clusters,
making it O(n). For a simple single-character check, pattern matching on
the result of String.graphemes/1 is more expressive and idiomatic.
This rule automatically rewrites the comparison to use match?/2 with
String.graphemes/1, which produces a clean boolean result that works
in any expression context.
Bad
if String.length(target_char) != 1 do
raise ArgumentError, "expected a single character"
end
String.length(s) == 1
1 === String.length(s)Good
if not match?([_], String.graphemes(target_char)) do
raise ArgumentError, "expected a single character"
end
match?([_], String.graphemes(s))