Chains work, but this is not necessarily the best answer in the general case, especially because it hides the point of failure. Instead, I would suggest smoothing out the tests by inverting the logic so that it fails.
if (!pa) return Fail("No pa"); B* pb = pa->b(); if (!pb) return Fail("No pb"); C* pc = b->c(); if (!pc) return Fail("No pc"); pc->DoSomething();
The same, but flat and easy to read. In addition, since it immediately handles the case of a failure, it does not fall into the else , which you may never find to write.
In this example, I assumed that you do not want to simply fail, so I added Fail as an assistant, which registers the text and returns false. You can also just throw an exception. In fact, if various methods signaled their failure, throwing an appropriate exception instead of returning null, then all this would be unnecessary. If silent failure was desired, then a null object pattern would be appropriate.
Steven sudit
source share