Null Safe dereferencing in Java like ?. in Groovy using Maybe monad
Posted
by Sathish
on Stack Overflow
See other posts from Stack Overflow
or by Sathish
Published on 2010-05-24T20:41:08Z
Indexed on
2010/05/25
9:11 UTC
Read the original article
Hit count: 316
I'm working on a codebase ported from Objective C to Java. There are several usages of method chaining without nullchecks
dog.collar().tag().name()
I was looking for something similar to safe-dereferencing operator ?. in Groovy instead of having nullchecks
dog.collar?.tag?.name
This led to Maybe monad to have the notion of Nothing instead of Null. But all the implementations of Nothing i came across throw exception when value is accessed which still doesn't solve the chaining problem. I made Nothing return a mock, which behaves like NullObject pattern. But it solves the chaining problem.
Is there anything wrong with this implementation of Nothing? [http://github.com/sathish316/jsafederef/blob/master/src/s2k/util/safederef/Nothing.java]
As far as i can see 1. It feels odd to use mocking library in code 2. It doesn't stop at the first null. 3. How do i distinguish between null result because of null reference or name actually being null? How is it distinguished in Groovy code?
© Stack Overflow or respective owner