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?"
> getAccount().getContact().getPhoneNumber() Every time I see people "deal" with this problem, it looks like this: if (getAccount() != null && getAccount().getContact() != null && getAccount().getContact.getPhoneNumber() != null) { // do something } // don't put an else condition in, just keep going and let the program // produce the wrong result in a confusing way when it happens in production I actually blame rampa…
C# at least has null propagation and pattern matching that can make that line:
if (getAccount()?.getContact()?.getPhoneNumber() is string pn) {
// do something with `pn`
}
The "idiomatic" C# way would also include properties: if (GetAccount()?.Contact?.PhoneNumber is string pn) {
// do something with `pn`
}