<div dir="ltr"><br><br><div class="gmail_quote"><div dir="ltr">On Sat, Sep 9, 2017 at 12:04 PM Jim Ingham <<a href="mailto:jingham@apple.com">jingham@apple.com</a>> wrote:<br></div><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex"><div style="word-wrap:break-word"><div><br></div><div>I disagree here.  If you can reasonably unwind from an error you should do so even if you can’t figure out how you could have gotten an answer you didn’t expect.  If an API is returning a pointer to something you should assume it might return nullptr unless the API explicitly states otherwise.  </div></div></blockquote><div>But that's exactly what an assert is.  It's an explicit statement by the API about what should happen.  Which is why by adding them liberally, these assumptions can then be propagated all the way up through many layers of the code, vastly simplifying the codebase.</div><div><br></div><div>if you have</div><div><br></div><div>void *foo(int x) {</div><div>  // do some stuff</div><div><br></div><div>  assert(x < 0 || foo != nullptr);</div><div>}</div><div><br></div><div>Then you're documenting that if x is greater than 0, the caller doesn't need to check the return value for nullptr.  Now instead of this:</div><div><br></div><div>void *bar(unsigned x) {</div><div>  void *ptr = foo(x);</div><div>  if (!ptr) {</div><div>    // log an error</div><div>    return nullptr;</div><div>  }</div><div>  return ptr;</div><div>}</div><div><br></div><div>You just have</div><div><br></div><div>void *bar(unsigned x) {</div><div>  void *ptr = foo(x);</div><div>  assert(x);</div><div>  return x;</div><div>}</div><div><br></div><div>And now the caller of bar doesn't have to check either.  The code has greatly reduced complexity due to the butterfly efflect of propagating these assumptions up.</div><div><br></div><div>This is a simple example but the point is that building assumptions into your API is a good thing, because you can enforce them and it vastly simplifies the code.</div></div></div>