foo.bar().baz().qux()
...Grrrrr! foo.bar().baz().qux()
...Grrrrr! foo >>= bar >>= baz >>= quux
and there would never be a NullPointerException, because the >>= function could react appropriately when null was encountered!foo?.bar()?.baz?.quux
What other languages have this kind of shortcut?
$ irb
>> def nil.method_missing *args
>> nil
>> end
=> nil
>> a = nil
=> nil
>> a.b.c.d
=> nil
>>Clever? Insane? Horribly un-portable and prone to breakage depending on compiler, libc, and OS versions? All of the above!
(And yes, I have seen this coding style used in multiple projects at a major corporation. It was a favorite of a coder-turned manager, which means it tended to sneak in on any project he supervised.)
Yeah, you already said it was C++.
if (foo != null) if (bar.bar() != null) if (foo.bar().baz() != null) {
...
worked = true;
}
if (false == worked ) {/*to do*/}
But, staying on the happy path until you can demo something is often useful. I think the problem is how you transition from demo to production worthy code.a = foo.bar() will always evaluate to true as the assignment shouldn't ever fail. Of course, in compiled languages I'm sure there will need to be a declaration of 'a' but if there is a possibility to reuse temp variables then could work.
However, if you are coding in C/C++ (and to a similar extent Java, there really is no way around it.
This could be an example of why hybrid functional, imperative, and object oriented languages are becoming popular because the programmer can pick the paradigm that most suits the problem.
Could become:
Bar bar = foo.bar();
if(bar == null) handleBarNull();
else {
Baz baz = bar.baz();
if(baz == null) handleBazNull();
else {
//(assuming qux is a value)
return baz.qux() * 2;
}
}Say you have
public int doubleFooBarBazQux(Foo foo) {
return foo.bar().baz().qux() * 2;
}
That might throw a NPE, but what's the alternative? public int doubleFooBarBazQux(Foo foo) throws NullPointerException {
try {
return foo.bar().baz().qux() * 2;
}
catch(NullPointerException e){
throw new NullPointerException(e.getMessage());
}
}
If only there was a right-click option for "improve quality"...Code like that is really common, and, unfortunately, so are blank 'catch' sections.