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?
public class Nothing<T> implements Maybe<T> {
private Class<T> klass;
public Nothing(Class<T> klass) {
this.klass = klass;
}
@Override
public T value() {
return mock(klass, Mockito.RETURNS_DEEP_STUBS);
}
}
As far as I can see
- It feels odd to use mocking library in code
- It doesn’t stop at the first null.
- How do i distinguish between null result because of null reference or name actually being null? How is it distinguished in Groovy code?
I wouldn’t really recommend just checking for the nulls. Really, I recommend not even ever returning null, but instead throwing exceptions.
In either case, you are not going to make the code any faster by doing this null object method, and I think you’ll just end up confusing someone just because you want to replicate the feature of a different programming language. I think you should just adapt to the language you’re using.