4 ms·
If you're going for "each line of code should do exactly one thing", you'd probably prefer that as if(foo) { if(foo->bar) { //whatever
by JonathonW 5y ago
If you're going for "each line of code should do exactly one thing", you'd probably prefer that as
if(foo) {
if(foo->bar) {
//whatever
}
}
separating out the null check and the actual conditional. More lines of code and more nesting, yes, but, if you're trying to strictly adhere to a one thing/one line principle, you probably don't care.
Short-circuit 'or' is a little harder to avoid (if you specifically want the short-circuit behavior), since you'd have to duplicate the code in the body of the if. But that doesn't come up as often IME.
- kbelder 5y agoYep, I'd prefer that option, despite its wordiness. Obviously this depends a lot on individual preferences, and in this simple example it really doesn't make a lot of difference. I imagine the compiler spits out pretty similar code either way. It's more just a recognition of my own limitations... I'm a lot less likely to screw up something up, the more explicitly it's written out. When I was a younger man, I wouldn't have bothered.
- zarzavat 5y agoThe problem with that code and the reason that it is often considered bad C++ practice is that it is very easy to accidentally move the inner conditional outside of the outer conditional, thus creating undefined behaviour. Putting the null check in the same line as the usage means that it is much harder to separate them accidentally.
- bobbyi_settv 5y agoThat technique doesn't work (as well) when you want a single "else" block that is used when either of the conditions is false, which I think is pretty common for this sort of conditional