This is just covering up design problems. NPEs show you were you have design deficiencies. If you have getAccount().getContact().getPhoneNumber() and contact is null, you'll get an NPE. The question shouldn't be: "How do I shove the NPE under the rug for the next 1337 coder to deal with?", the question should be: "How did I initialize an Account without a Contact?"
I've brought it up when using Swift and Kotlin and it takes so much energy for people to realize that safety operators, which feel really really good to use, accidentally sweep up major issues
People assume you're missing something when you explain that they need to get more comfortable with force unwrapping (which is intentionally introducing a NPE)
-
But for example, if you have getAccount().getContract().getPhoneNumber() so you can show it in a settings page, you should not throw an NPE. You can easily correct the issue in a non-invariant breaking way by say defaulting to "" in the UI.
But if you have getAccount().getContract().setSomeFieldWithRealWorldImportance(true), you should either be force unwrapping or returning a Result type, and ensuring someone is actually handling it with a hard stop on the user.
The problem is reality is often much more subtle than "doSomethingImportant()".
For example, I worked on an iOS app that was used for medical work, and one habit iOS devs had was wrapping access to weak references to objects with a null safety:
So they were super comfortable writing things equivalent to viewController?.showSomeDialog()
because in most situations crashing over lifecycle issues is a bad idea... but here we could be creating incorrect output in a highly sensitive situation.
"someDialog" could be "Drug interaction between X and Y detected" for example, but the mental patterns wouldn't detect that a safety operator was hiding that.
It was better for the app to crash than silently hide that information, since at least then it'd be known the app was in an invalid state.
-
Now the problem is here devs start to think "well I'm not making medical apps" or "well I wouldn't make that mistake"...
But go through any moderately large codebase and you will find important user actions that silently fail where a crash would actually serve the user better.
It's how to convince people that a hard crash can ever be good though.