Hello
I've been running TPTP static analysis in Eclipse over my code, and it
complains about:
"Always place constants on the left side of the equals()"
Example code:
if (fileExtension.substring(0, 1).equals(".")){
fileExtension = fileExtension.substring(1); // get rid of the dot
}
wants to be fixed to:
if (".".equals( fileExtension.substring(0, 1) )){
fileExtension = fileExtension.substring(1); // get rid of the dot
}
Why is it better to have constants on left side of equals() ?
In my opinion the first code is much more readable than the second. Is
readability of higher priority than such coding best practices?
Thanks for your answers
Philipp
Daniel Dyer - 10 Apr 2007 14:03 GMT
> Hello
> I've been running TPTP static analysis in Eclipse over my code, and it
[quoted text clipped - 12 lines]
>
> Why is it better to have constants on left side of equals() ?
It's to avoid NullPointerExceptions. If a method can return null it may
cause problems if you try to invoke the equals method on the returned
reference. By ensuring that you call equals on the String constant and
pass the (possibly null) value as an argument, you should never get a
NullPointerException.
> In my opinion the first code is much more readable than the second. Is
> readability of higher priority than such coding best practices?
I wouldn't blindly follow "best practices" just because somebody says they
are a good idea. As you have acknowledged by asking the question, it's
best to find out the justifications and make up your own mind.
Dan.

Signature
Daniel Dyer
http://www.uncommons.org
Chris Uppal - 10 Apr 2007 14:31 GMT
> In my opinion the first code is much more readable than the second. Is
> readability of higher priority than such coding best practices?
In my opinion, yes -- readability is nearly always more important than such
"micro" practices.
(And, as an aside, I don't think that automated tools should ever be taken as
arbiters of best practice. Indeed, I have never found them to be very useful
even as mere sources of suggestions for consideration.)
-- chris
Wojtek - 10 Apr 2007 15:20 GMT
Philipp wrote :
> Hello
> I've been running TPTP static analysis in Eclipse over my code, and it
[quoted text clipped - 5 lines]
> fileExtension = fileExtension.substring(1); // get rid of the dot
> }
Or you could have:
if (fileExtension.startsWith("."))
{
fileExtension = fileExtension.substring(1); // get rid of the dot
}

Signature
Wojtek :-)
Philipp - 11 Apr 2007 06:17 GMT
> Philipp wrote :
>> Hello
[quoted text clipped - 13 lines]
> fileExtension = fileExtension.substring(1); // get rid of the dot
> }
Absolutely :-)
When I wrote this, I didn't know startsWith() yet...
Thanks to all for your answers
Phil