Credence.Pattern.NoStringLengthForEmptyCheck (credence v0.8.0)

Copy Markdown

Rewrites String.length(s) == 0 (and != 0, and the flipped operand order) to the O(1) empty-string check s == "" / s != "" — but ONLY when s is provably a binary.

String.length/1 traverses the whole string (O(n)) just to ask "is it empty?". s == "" answers that in O(1). The two agree for every string s, but String.length/1 raises on a non-string while s == "" returns false, so a bare variable would diverge on non-string input. The rule therefore fires only when the argument is unambiguously a binary:

This is the empty-string analog of no_enum_count_for_length (which narrows to provably-list arguments).

Bad

String.length(String.trim(line)) == 0
0 == String.length(downcased)   # when `downcased = String.downcase(x)`
String.length(a <> b) != 0

Good

String.trim(line) == ""
"" == downcased
a <> b != ""