> -----Original Message-----
> From: Berin Loritsch [mailto:[EMAIL PROTECTED]
> Sent: Freitag, 7. März 2003 18:50
> To: [EMAIL PROTECTED]; [EMAIL PROTECTED]
> Subject: Re: Coding style question: backwards null checks
> 

> > if ( "something".equals(stringToCompare) {
> >    ...
> > }
> > 
> > IMO it seems more straightforward and easier to read if it's:
> > 
> > if ( stringToCompare.equals("something") ) {
> >    ...
> > }
>
 
> Actually, this *does* have a purpose.  In the event that
> stringToCompare is null, then you would get spurious
> NullPointerExceptions that are not always easy to trace.
> 
> The "something".equals(somethingElse) guarantees that
> you won't get the NullPointerException every time without
> resorting to the longer form of:
> 
> if ( stringToCompare != null && 
> stringToCompare.equals("something") ) {
>      ....
> }
> 
> It's a lot more typing to be _truly_ functionally
> equivalent.  The compiler cannot guarantee that
> the stringToCompare variable is never null, so it
> will not give you a warning.

I'd say this is no longer a matter of taste but of methodology.  
If you write

  stringToCompare != null && stringToCompare.equals("something") 

you state clearly that you expect it may be null and how to deal
with it.  Saying that you write 

  "something".equals(stringToCompare)

because you *know* from long years of experience that it is 
equivalent, gains you an entry in the Java obfuscation contest.

(I am fairly seasoned Java programmer but I had to look up docs
to convince myself that equals(null) wouldn't throw an exception.)

A null string being different to any other string may be in some
cases a useful convention, in other cases it hides a logic error.

Let the code state clearly what your intentions are and let it fail
with NPE, if you don't expect handle nulls.

NB my stanza for repeatedly writing non-null checks is:

  if( stringToCompare == null )
      stringToCompare = "";
  if( stringToCompare.equals("something") ) {
      ...
  }

Cheers, Alfred.

This message is for the named person's use only. It may contain
confidential, proprietary or legally privileged information. No
confidentiality or privilege is waived or lost by any mistransmission.
If you receive this message in error, please notify the sender urgently
and then immediately delete the message and any copies of it from your
system. Please also immediately destroy any hardcopies of the message.
You must not, directly or indirectly, use, disclose, distribute, print,
or copy any part of this message if you are not the intended recipient.
The sender's company reserves the right to monitor all e-mail
communications through their networks. Any views expressed in this
message are those of the individual sender, except where the message
states otherwise and the sender is authorised to state them to be the
views of the sender's company. 


Reply via email to