Code smell candidate?

Answered

Today I stumbled upon this code:

if (string != null && string.chatAt(0) == 'x') {
...
}

Which will throw an index out of bound exception when string is empty.

The intention was to write this instead:

if (string != null && string.startsWith("x")) {
...
}

IDEA didn't warn that the code may throw an exception or suggest rewriting it using startsWith. Potential candidate?

Just my fiddy cents.

0
1 comment

Created feature request for that: https://youtrack.jetbrains.com/issue/IDEA-273681

But it is shelved for now. See this comment: 

Well, it could be known from elsewhere that the string is never empty. Also, in case if empty string unexpectedly appears here, it's unclear that silently bypassing if statement (or visiting the else branch if any) would be intended behavior. The suggestion changes the code semantics and I'm not sure this change is always desired...

0

Please sign in to leave a comment.