Test Cases AND assertion statements

defensive-programming

Solution

The problem with trusting just Asserts, is that they may be turned off in a production environment. To quote the wikipedia article:

Most languages allow assertions to be enabled or disabled globally, and sometimes independently. Assertions are often enabled during development and disabled during final testing and on release to the customer. Not checking assertions avoiding the cost of evaluating the assertions while, assuming the assertions are free of side effects, still producing the same result under normal conditions. Under abnormal conditions, disabling assertion checking can mean that a program that would have aborted will continue to run. This is sometimes preferable. Wikipedia

So if the correctness of your code relies on the Asserts to be there you may run into serious problems. Sure, if the code worked during testing it should work during production... Now enter the second guy that works on the code and is just going to fix a small problem...

Problem

The code in this question made me think ``` assert(value>0); //Precondition if (value>0) { //Doit } ``` I never write the if-statement. Asserting is enough/all you can do. "Crash early, crash often" CodeComplete states: - The assert-statement makes the application Correct - The if-test makes the application Robust I don't think you've made an application more robust by correcting invalid input values, or skipping code: ``` assert(value >= 0 ); //Precondition assert(value <= 90); //Precondition if(value < 0) //Just in case value = 0; if (value > 90) //Just in case value = 90; //Doit ``` These corrections are based on assumptions you made about the outside world. Only the caller knows what "a valid input value" is for your function, and he must check its validity before he calls your function. To paraphrase CodeComplete: "Real-world programs become too messy when we don't rely solely on assertions." Question: Am I wrong, stuborn, stupid, too non-defensive...

Original source

Related problems