toward null-safe cookie cutter Comparators

R

Roedy Green

I don't know how many people still subscribe, but I posted over in
comp.lang.advocacy a request on your preferred way of writing
null-safe Comparators.

I have shown a number of possible snippets. Please let me know what
you think and see if you can come up with something better - fast,
terse and comprehensible.

I will incorporate the feature in the CompatorCutter for cranking out
Java source code for custom Comparators.
 
T

Tom Anderson

I don't know how many people still subscribe, but I posted over in
comp.lang.advocacy a request on your preferred way of writing null-safe
Comparators.

Roedy means (a) comp.lang.java.advocacy, and (b) comparators for objects
some of whose fields may be null (ie i don't think he's concerned with
comparators where one of the arguments may be null).

For those of you who are into Google Groups, the other thread is here:

http://groups.google.com/group/comp.lang.java.advocacy/browse_thread/thread/83db33bcbd51905d#

Approaches involving nested if-elses will be more efficient, but always
strike me as rather awkward.
I have shown a number of possible snippets. Please let me know what you
think and see if you can come up with something better - fast, terse and
comprehensible.

I personally rather like your third option:

final String aSpecies = a.species == null ? "" : a.species;
final String bSpecies = b.species == null ? "" : b.species;
return aSpecies.compareTo( bSpecies );

Perhaps even pushing the duplicated denullification into a little method.
Note that when the Elvis operator makes it into Java, you will be able to
write:

return (a.species ?: "").compareTo(b.species ?: "");

Should you so wish.

I'm also happy to see:

if (a.species == b.species) return 0;

as a guard clause ahead of the main comparison, which catches, as you say,
both the both-null and identical-objects cases.

tom
 
R

Roedy Green

return aSpecies.compareTo( bSpecies );

Perhaps even pushing the duplicated denullification into a little method.
Note that when the Elvis operator makes it into Java, you will be able to
write:

This whole business of multiple representations for empty.
Acch(Imagine a Yiddish sound of contempt).

null, "", " "

I have have always felt this looseness was like a trap a child digs to
catch the mailman.

There are no assertions defining what a given method parm will accept
(though IntelliJ is pushing @Nullable and #NotNull) There is not even
a JavaDoc convention to warn you if a method might produce which
combinations of the three.

see http://mindprod.com/jgloss/empty.html

From a machine efficiency point of view, null is probably the best
convention. Empty is usually a special case anyway. It might as well
be easy to detect.

From a coding safety point of view "" is best. It will generaly work
sensibly if passed to a method expecting a substantial string, where
there is a good chance it would fail on null.

Maybe we need some sort of Generics to declare what methods
produce/consume and have thecompiler tell you if you are potentially
doing something dangerous at compile time.

I once drove my boss nearly to distraction, because I was convinced
the problem with the project was random empty string representations.

The DWIM school of thinking

Way back I wrote suggesting a DWIM approach to taming the dreaded
NullPointerException. It is inspired more by scripting languages.

Thing a = null.

a.getAString() --> null
a.getTemp() --> 0.0d;
a.getDufusOBject --> null

a.doSomething() --> does nothing

a.doSomethingElse ( engage( 42 ) ); --> invokes engage function
( in my mind checking a and store come after RHS evaluation,
If I had my way Java would a much stricter left to right
evaluation order)

For more explicit use, you would replace the . operator with .? to
indicate you wanted to do a dummy var fetch/method call or none at all
if "a" were null. When I thought about extending that I though
perhaps classes should use dummy objects in place of null to bypass
this sort of trouble at clealr all that null-handling clutter,just
letting the null-handling logic come out in the wash most of the
time.

The thinking is a bit like the way there are are multiple flavours of
NaN in IEEE floating point, and the value appearing in calculation is
not the end of the world. The null just propagates.

P.S.
Apparently the eponymous Elvis rarely went to Las Vegas. I have not
tracked down who he is. People were often puzzled when I talked about
the McCarthy or operator || the bitwise | one.
see http://mindprod.com/jgloss/or.html The McCarthy I refer to
probably never met Candice Bergen and died recently.
 
D

Daniel Pitts

This whole business of multiple representations for empty.
Acch(Imagine a Yiddish sound of contempt).

null, "", " "

I have have always felt this looseness was like a trap a child digs to
catch the mailman.

There are no assertions defining what a given method parm will accept
(though IntelliJ is pushing @Nullable and #NotNull) There is not even
a JavaDoc convention to warn you if a method might produce which
combinations of the three.

see http://mindprod.com/jgloss/empty.html

From a machine efficiency point of view, null is probably the best
convention. Empty is usually a special case anyway. It might as well
be easy to detect.

From a coding safety point of view "" is best. It will generaly work
sensibly if passed to a method expecting a substantial string, where
there is a good chance it would fail on null.
The real problem is handling User Input and Form Submission. The empty
string ("") signifies that a field was submitted but not filled with any
value. A null value signifies that the field was not submitted at all.

Unfortunately when processing such forms the null value, an empty
string, and an all whitespace string, usually need to be treated the
same way. Invalid input.

The truth of the matter is that should all be handled by the
binding/validation layer, and then normalized to exactly one such value
(possibly null). Often they should be converted to a domain object
anyway, rather than kept as "just a string".
Maybe we need some sort of Generics to declare what methods
produce/consume and have thecompiler tell you if you are potentially
doing something dangerous at compile time.

I once drove my boss nearly to distraction, because I was convinced
the problem with the project was random empty string representations.
I've seen projects where a *core* library had a method "isNull" defined
thusly:

public boolean isNull(Object o) {
if (o == null) return true;
String s = String.valueOf(o);
if (s.trim().length == 0) {
return true;
}
if ("null".equals(s)) return true;
if ("(null)".equals(s)) return true;
}

Obviously, someone was told that "null" and "(null)" were appearing
somewhere and causing problems. Instead of tracking down the source,
they littered the codebase with these "isNull" checks. I should have my
legal name changed to "Null Null", and see how many forms on the web
reject my name :)
The DWIM school of thinking

Way back I wrote suggesting a DWIM approach to taming the dreaded
NullPointerException. It is inspired more by scripting languages.

Thing a = null.

a.getAString() --> null
a.getTemp() --> 0.0d;
a.getDufusOBject --> null

a.doSomething() --> does nothing

a.doSomethingElse ( engage( 42 ) ); --> invokes engage function
( in my mind checking a and store come after RHS evaluation,
If I had my way Java would a much stricter left to right
evaluation order)
NPE is one of the best things that can happen. It tells you immediately
what needed to have a value but didn't. Rather than the end result of a
chain of null operations that failed deeply in the project.

Imagine the following:

// Commonly used library method handleThing.
void handleThing(Thing t) {
AnotherThing at = t.getAnotherThing()
doSomething(at);
}

void doSomething(AnotherThing t) {
saveToDatabase(t.getName(), t.getId());
}

Now, imagine you get a database error (or worse, no error, just bad null
records). You have *no* trace whatsoever of which call of handleThing
caused the problem. This is similar to the potential problem caused by
NaN propagation.
 
R

Roedy Green

NPE is one of the best things that can happen

I really enjoyed that post. It might have been composed by Mark
Twain were he a computer programmer.

Amen. One of the almost miraculous things about Java is once you get
rid of the compile errors, and once you stop triggering NPEs, there
very good chance you have nailed all the bugs.

There are situations where null is expected and it is just a hassle to
explicitly deal with it, and other places where its presence is a sign
of pathology.

Whatever changes you make to the language should not make you treat
everything the same way.
 
K

kensi

I've seen projects where a *core* library had a method "isNull" defined
thusly:

public boolean isNull(Object o) {
if (o == null) return true;
String s = String.valueOf(o);
if (s.trim().length == 0) {
return true;
}
if ("null".equals(s)) return true;
if ("(null)".equals(s)) return true;
}

Shocking, if true, since the above code won't compile.
Obviously, someone was told that "null" and "(null)" were appearing
somewhere and causing problems. Instead of tracking down the source,
they littered the codebase with these "isNull" checks. I should have my
legal name changed to "Null Null", and see how many forms on the web
reject my name :)

Why go to the hassle of changing your legal name? It's not like giving
false information to large corporate marketing departments^W^W^W^Wweb
forms is an offense under the law or anything. ;) At most it's a TOS
violation and the account you create won't last long (cf. Facebook,
Google Plus).
Imagine the following:

// Commonly used library method handleThing.
void handleThing(Thing t) {
AnotherThing at = t.getAnotherThing()
doSomething(at);
}

Comment above is wrong, should be
// Commonly used Law of Demeter violation
HTH. :)
 
D

Daniel Pitts

Shocking, if true, since the above code won't compile.
Well, I did "copy and paste" from memory, and my clipboard is obviously
fallible. There should be a "return false;" immediately prior the final
"}".
Why go to the hassle of changing your legal name? It's not like giving
false information to large corporate marketing departments^W^W^W^Wweb
forms is an offense under the law or anything. ;) At most it's a TOS
violation and the account you create won't last long (cf. Facebook,
Google Plus).
Because if I change my legal name, then I have legal recourse for them
discriminating against me ;-).
Comment above is wrong, should be
// Commonly used Law of Demeter violation
HTH. :)

Perhaps in this case, but the point still stands that null propagation
can make bug diagnosis much more difficult.
 
L

Lew

kensi said:
Shocking, if true, since the above code won't compile.

He said, "thusly", not "thus", thus allowing a little room for transcription error, in this case the omission of the catch-all 'return false;'.

His main point, that even with the correction the routine is stupid, is not damaged.
 
G

Gene Wirchenko

On Wed, 16 Nov 2011 13:47:57 -0800, Daniel Pitts

[snip]
Because if I change my legal name, then I have legal recourse for them
discriminating against me ;-).

<perry mason>
"Your Honour, we have documented proof in writing of the
defendant's intent to commit computer hacking. Exhibit A is a name
change application that the defendant ..."

[snip]

Sincerely,

Gene Wirchenko
 
L

Lew

Gene said:
Daniel Pitts wrote:
[snip]
Because if I change my legal name, then I have legal recourse for them
discriminating against me ;-).



"Your Honour, we have documented proof in writing of the
defendant's intent to commit computer hacking. Exhibit A is a name
change application that the defendant ..."

[snip]

Cute, but given that Daniel's approach involves no login to any computer systems, no coding, no scripting nor any other computer activity of his own, it would be very difficult indeed to make a case that he's engaging in computer hacking. In fact, he would make such a change with no certain knowledge that computer systems have a weakness, much less any demonstrable attempt to exploit such weakness.

http://xkcd.com/327/
 
G

Gene Wirchenko

Gene said:
Daniel Pitts wrote:
[snip]
Why go to the hassle of changing your legal name? It's not like giving
false information to large corporate marketing departments^W^W^W^Wweb
forms is an offense under the law or anything. ;) At most it's a TOS
violation and the account you create won't last long (cf. Facebook,
Google Plus).
Because if I change my legal name, then I have legal recourse for them
discriminating against me ;-).
"Your Honour, we have documented proof in writing of the
defendant's intent to commit computer hacking. Exhibit A is a name
change application that the defendant ..."

[snip]

Cute, but given that Daniel's approach involves no login to any computer
systems, no coding, no scripting nor any other computer activity of
his own, it would be very difficult indeed to make a case that he's
engaging in computer hacking. In fact, he would make such a change
with no certain knowledge that computer systems have a weakness, much
less any demonstrable attempt to exploit such weakness.

Well, he might be typing into some system.

"Your Honour, the defendant's lawyer is obviously trying to get
his client off on a technicality. This is tantamount to admitting
guilt."

Spoilsport. <BEG>

Sincerely,

Gene Wirchenko
 
A

Andreas Leitgeb

Lew said:
He said, "thusly", not "thus", thus allowing a little room
for transcription error, in this case the omission of the
catch-all 'return false;'.

Funny. The missing parens after length caught my eye, but
the missing return at the end didn't. :)
 
T

Tim Slattery

Paul Cager said:
Obviously, someone was told that "null" and "(null)" were appearing
somewhere and causing problems. Instead of tracking down the source,
they littered the codebase with these "isNull" checks. I should have my
legal name changed to "Null Null", and see how many forms on the web
reject my name :)
[...]
Because if I change my legal name, then I have legal recourse for them
discriminating against me ;-).

Reminds me of: http://xkcd.com/327/


ROTFL!!!!
 
N

Nigel Wade

Why go to the hassle of changing your legal name? It's not like giving
false information to large corporate marketing departments^W^W^W^Wweb
forms is an offense under the law or anything. ;) At most it's a TOS
violation and the account you create won't last long (cf. Facebook,
Google Plus).

Really?

http://www.theregister.co.uk/2008/11/27/myspace_mother_guilty/

Note, she was NOT convicted of "cyber bullying", but of fraudulently
accessing MySpace by providing false personal information. If just goes
to show how useful those "knee-jerk" laws can be, when suitably abused.
 
S

spk

One old Derbyshire sock popped a load of hogwash woven under "kensi"
Shocking, if true, since the above code won't compile.
the pedant in you rises again?
Why go to the hassle of changing your legal name?
you are lost for reason, Paul?
How ironic.
It's not like giving false information to large corporate marketing departments^W^W^W^Wweb
forms is an offense under the law or anything. ;)

failing to render "purpose" into the panorama before you, Paul?
At most it's a TOS >violation and the account you create won't
last long (cf. Facebook, Google Plus).
classic erroneous supposition.

Comment above is wrong, should be
// Commonly used Law of Demeter violation
HTH. :)

now just which of Murphy's list are you going to preserve for CJLP from your
portfolio of known troll identities?

--

Murphy's list applies;

".--- . ... ..- ..." <[email protected]>
00101010 <[email protected]>
3k7e4intna <[email protected]>
3x7r4vagan <[email protected]>
3x+r4v4g4n <[email protected]>
Alice <[email protected]>
Arne Këndoj <[email protected]>
Boojum <[email protected]>
B1ll Gat3s <[email protected]>
A Canuck <[email protected]>
Canuck <[email protected]>
Cindy <[email protected]>
ClassCastException <[email protected]>
Cthun <[email protected]>
Chad Carmichael <[email protected]>
dA.b0mB <[email protected]>
dark-zark-fark <[email protected]>
Deep Green <[email protected]> (forgery)
Deeyana <[email protected]>
De Lurker <[email protected]>
Derek Yancey <[email protected]>
Extravagan <[email protected]>
Eight of Seventeen <[email protected]>
Ferdinand the -14th <[email protected]>
Four of Seventeen <[email protected]>
Fuschia, President-Elect of the Bright Purplish-Green Council
<[email protected]>
George Arctos <[email protected]>
Greg Kelly <[email protected]>
Greg Sandoval <[email protected]>
Gheerax IV <[email protected]>
Handkea fumosa <[email protected]>
Hieronymus S. Freely <[email protected]>
Hydrocon <[email protected]>
Henry Harrison <[email protected]>
Henderson <[email protected]>
Heike Svensson <[email protected]>
Harry Greer <[email protected]>
Janie Zanie <[email protected]>
Jerry Gerrone <[email protected]>
John Kirkpatrick XVII <[email protected]>
Katie Gerrolds <[email protected]>
Kevin Hadron <[email protected]>
kensi <[email protected]>
KitKat <[email protected]>
Meerkats <[email protected]> (forgery)
Mister Scott <[email protected]>
Movable Hype <[email protected]>
Mrs. Danforth <[email protected]>
Mike Faramis <[email protected]>
Mamac <[email protected]>
Nancy 3 <[email protected]>
Nancy 4 <[email protected]> (forgery)
Nebulous <[email protected]>
Nightcrawler <[email protected]>
Nougat Surprise <[email protected]>
Orange Green <[email protected]>
Purpleswandir <[email protected]>
Retahiv Oopsiscame <[email protected]>
RichB <[email protected]>
(e-mail address removed)
SFTV_troll <[email protected]>
Some Guy <[email protected]>
Sulfide Eater <[email protected]>
<supercalifragilisticexpialadiamaticonormalizeringelimatisticantations@averylongandannoyingdomainname.com>
Spock <[email protected]>
Series Expansion <[email protected]>
Seamus MacRae <[email protected]>
sproing <[email protected]>
Snicker-snack! <[email protected]>
Tim <[email protected]>
Thursday's Leftovers <[email protected]>
thoolen <[email protected]>
thoolen <[email protected]>
thoolen <[email protected]>
<[email protected]>
Willy Wonka <[email protected]>
Zapotec <[email protected]>

Truth in Conclusions.
"At some point, can't we find a bit
of charity for a guy who looks to be in for some real hellish times up
ahead?"
http://groups.google.com/group/alt.fan.kia-mennie/msg/c9946955fb73b48c?dmode=source
 
A

Andreas Leitgeb

spk said:

to Lew:
spk *didn't* respond to a posting of Daniel Pitts.

As you're filtering away a lot, you should get into the habit
of NOT-assuming that a followup was always to the preceding
article in your newsclient's display.
 
S

spk

to Lew:
spk *didn't* respond to a posting of Daniel Pitts.

As you're filtering away a lot, you should get into the habit
of NOT-assuming that a followup was always to the preceding
article in your newsclient's display.

thank you kindly.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,983
Messages
2,570,187
Members
46,747
Latest member
jojoBizaroo

Latest Threads

Top