Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Java > toward null-safe cookie cutter Comparators

Reply
Thread Tools

toward null-safe cookie cutter Comparators

 
 
Roedy Green
Guest
Posts: n/a
 
      11-13-2011
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.
--
Roedy Green Canadian Mind Products
http://mindprod.com
I can't come to bed just yet. Somebody is wrong on the Internet.
 
Reply With Quote
 
 
 
 
Tom Anderson
Guest
Posts: n/a
 
      11-13-2011
On Sun, 13 Nov 2011, Roedy Green wrote:

> 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....b33bcbd51905d#

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

--
No man ever steps in the same river twice, for it's not the same river
and he's not the same man. -- Heraclitus
 
Reply With Quote
 
 
 
 
Roedy Green
Guest
Posts: n/a
 
      11-14-2011
On Sun, 13 Nov 2011 17:59:54 +0000, Tom Anderson
<(E-Mail Removed)> wrote, quoted or indirectly quoted someone who
said :

>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.
--
Roedy Green Canadian Mind Products
http://mindprod.com
I can't come to bed just yet. Somebody is wrong on the Internet.
 
Reply With Quote
 
Daniel Pitts
Guest
Posts: n/a
 
      11-14-2011
On 11/14/11 10:28 AM, Roedy Green wrote:
> On Sun, 13 Nov 2011 17:59:54 +0000, Tom Anderson
> <(E-Mail Removed)> wrote, quoted or indirectly quoted someone who
> said :
>
>> 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.

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.

> 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.


 
Reply With Quote
 
Roedy Green
Guest
Posts: n/a
 
      11-15-2011
On Mon, 14 Nov 2011 10:55:11 -0800, Daniel Pitts
<(E-Mail Removed)> wrote, quoted or indirectly
quoted someone who said :

>>

>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.
--
Roedy Green Canadian Mind Products
http://mindprod.com
I can't come to bed just yet. Somebody is wrong on the Internet.
 
Reply With Quote
 
kensi
Guest
Posts: n/a
 
      11-16-2011
On 14/11/2011 1:55 PM, Daniel Pitts wrote:
> 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.
 
Reply With Quote
 
Daniel Pitts
Guest
Posts: n/a
 
      11-16-2011
On 11/16/11 9:50 AM, kensi wrote:
> On 14/11/2011 1:55 PM, Daniel Pitts wrote:
>> 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.

Well, I did "copy and paste" from memory, and my clipboard is obviously
fallible. There should be a "return false;" immediately prior the final
"}".
>
>> 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).

Because if I change my legal name, then I have legal recourse for them
discriminating against me .
>
>> 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.


Perhaps in this case, but the point still stands that null propagation
can make bug diagnosis much more difficult.
 
Reply With Quote
 
Lew
Guest
Posts: n/a
 
      11-16-2011
kensi wrote:
> Daniel Pitts wrote:
>> 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.


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.

--
Lew

> > 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.


 
Reply With Quote
 
Gene Wirchenko
Guest
Posts: n/a
 
      11-17-2011
On Wed, 16 Nov 2011 13:47:57 -0800, Daniel Pitts
<(E-Mail Removed)> 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 .


<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
 
Reply With Quote
 
Lew
Guest
Posts: n/a
 
      11-17-2011
Gene Wirchenko wrote:
> 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.

http://xkcd.com/327/

--
Lew
 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Olympus OM-D as a reaction to cookie-cutter DSLR "look" or Oly fan nostalgia? RichA Digital Photography 0 01-18-2012 02:08 PM
Talk about a cookie-cutter approach to photography! Bandicoot Digital Photography 2 02-12-2007 04:21 PM
sets with different comparators have same iterator type; standard? Dan Tsafrir C++ 13 10-30-2005 08:32 PM
Paper Cutter D McMillen Digital Photography 14 12-09-2003 04:58 AM
Re: Cranking out Comparators Tim Robinson Java 3 08-06-2003 03:25 AM



Advertisments