5 ms·
> getAccount().getContact().getPhoneNumber() Every time I see people "deal" with this problem, it looks like this: if (getAccount() != null && get
by commandlinefan 4y ago
> 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 rampant code generation and an adamant refusal to even consider object-oriented design for this problem - this sort of case ought to be handled by something like:
getAccount().callContact()
(or whatever you were going to do with the phone number when you got it). Insistence on generating code from SQL schemas or XML DTDs and then writing procedural code makes that pretty much impossible, though.
- colejohnson66 4y agoWith that awful `if` statement, you're calling the functions multiple times. It's negligible with the simple getters Java users use everywhere, but if that `getAccount()` call involved, say, the database, now you're making multiple calls when you don't have to. 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` }
- return_to_monke 4y agoSurprised that guard clauses weren't mentioned here yet, you could also write ``` if (account == null) { throw NoAccountException } if (account.contact == null) { throw AccountWithoutContactException } if (account.contact.phoneNumber == null) { throw ContactWithoutPhoneNumberException } // do stuff here ```
- commandlinefan 4y agoThat would be way better, but I've never seen it.
- kaba0 4y agoYou mention code generation as a problem, but it is actually a solution as well for this particular problem, I have really grown on mapstruct, where you create an interface declaratively specifying what field maps to what, and it will generate at compile time fast, efficient, correct code you might write by hand.
- deleted 4y ago[deleted]
- bcrosby95 4y agoThat sort of design easily leads to a god object. Class based OOD is way harder than that. There's a reason codebases are full of these train wrecks (the unofficial official name of the pattern). And it's not because of auto generation and/or laziness. It's because, despite what's on the tin, passable - nevermind good - OOD doesn't look anything like how we actually think of objects as humans.