Intention: single character startsWith should be replaced by charAt

In my code, I have:

if (replacedValue.startsWith("\"") && replacedValue.endsWith("\""))
return replacedValue.substring(1, replacedValue.length() - 1);

and IDEA is suggesting that this should be replaced with a single
character comparison.

I was originally going to ask for an intention to do that replacement,
then after doing it by hand, I started to wonder. I presume it would

if ((replacedValue.length()>0 && replacedValue.charAt(0)=='\"')
&&(replacedValue.length()>0 &&
replacedValue.charAt(replacedValue.length()-1) == '\"')) return
replacedValue.substring(1, replacedValue.length() - 1);

This does not really look better to me.

I know I can turn the inspection off, and I will likely do so, but I was
curious whether others agreed with my aesthetic.


Comment actions Permalink

I would never replace String.startsWith(char) with String.charAt(0) == char
(with relevant guard on length), unless a profiler told me this were where
my code spent 80% of its time.

To me,
tells me a lot more about the intention than
replaceValue.length() > 0 && replaceValue.charAt(0) == '\"'
(and is easier to read, too)

If I could I would add a warning on this inspection,
"the proposed change will definitely reduce readability of your code for a
very uncertain performance gain" :)


Comment actions Permalink

Like several other marginal performance inspections, this one will shortly be moved to a newly created "J2ME issues" category. While inappropriate for a J2SE or J2EE codebase, this inspection does make sense for those cases where every possible cycle matters. J2ME folk count cycles (and class file footprint) like a supermodel counts calories, so more stringent coding styles are reasonable, even at the cost of readability.

The J2ME category will be added as soon as it's possible for me to test my plugin in a sandbox, hopefully within the next few EAPs. Anyone with any J2ME inspections to suggest is strongly encouraged to drop me a line.

--Dave Griffith

Comment actions Permalink

Maybe send an rfe to Sun that you need an String.startsWith(char)?


Please sign in to leave a comment.