Credence.Rule.NoStringLengthForCharCheck (credence v0.2.0)

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 or using String.to_charlist/1 is more efficient and expressive.

Bad

if String.length(target_char) != 1 do
  raise ArgumentError, "expected a single character"
end

Good

case String.graphemes(target_char) do
  [_single] -> :ok
  _ -> raise ArgumentError, "expected a single character"
end

# Or use a function head with a guard on byte_size for ASCII:
def count_char(string, <<_::utf8>> = target) do
  ...
end