Question

We know that checking return values prevent our software from unexpected states. (You can see CWE definition.) But, we are sometimes sure about the return value. For example:

bool calculateSquareRootReturnFalseIfInputIsNegative(float input, float& output);
float calculateHypotenuse(float a, float b){
  float c2 = (a*a) + (b*b);
  float c;
  calculateSquareRootReturnFalseIfInputIsNegative(c2, c);
  return c;
}

The local variable c2 is always positive. So, calculateSquareRootReturnFalseIfInputIsNegative() always returns true. I shouldn't check its return value.

Finally, Is "check all return values not already known by caller" a valid idiom?

Thanks..

Was it helpful?

Solution

Is checking return values always required?

I don't think so; rather, they are almost always required. Proper error checking is very important, although sometimes it can admittedly be a pain in the neck.

However, your particular example does not describe a typical "perform operation that may fail and check the error" scenario. If your assumption about the sum of squares being positive is right (e. g. you expect this to be the case, and you don't permit e. g. NaN inputs), then what you are looking for is an assertion.

Assertions are used in situations exactly like this: when you have an operation that can sometimes fail, but you always pass it inputs for which it cannot possibly/shouldn't ever fail. Your program's internal consistency depends on this, so you assert, so that if this promise/assumption in your code ever breaks, you will get notified (i. e. the program crashes reliably at the earliest point it detects the inconsistency).

OTHER TIPS

That depends upon what you mean. If you mean is it required in order to output the correct result, the answer is no. If you mean is it required in order for the code to be well written, then the answer is yes.

Well written code is code that is unambiguous to the reader -- if I read your code and see you ignore a return value, I have to break out my psychic abilities and determine if you INTENTIONALLY or INADVERTANTLY ignored the return value in order to understand what you meant the code to do. My psychic abilities are notorious for returning ambiguous results.

More seriously, an empty if block (with or without a comment) makes it clear that you know about the return value (and that it wasn't for instance added as part of a refactoring) and that you considered what to do. It also provides a handy starting point to add the code to handle the return value if it turns out that it needs to be handled after all.

No. There is nothing idiomatic about error-handling-by-return-value, either in the callee side or the caller. Leave these terrible practices in the Stone Age where they belong.

You should write your functions to throw on failure. If you're using a library that hasn't been updated since 1972, then you need to wrap it to provide a usable interface.

Licensed under: CC-BY-SA with attribution
scroll top