If you believe that something can never happen in your code, use assertions to ensure that. Never go with assumptions only.
"This code won't be used 30 years from now, so two-digit dates are fine."
"This application will never be used abroad, so why internationalize it?"
Always avoid this kind of self-deception.
In C and C++, we have assert macros which check a boolean condition. Here is an example:
void writeString(char *string) {
assert(string != NULL);
...
}
This assert statement checks for a null string before executing the code inside the method. The execution stops when it encounters a null string.
While using assertions, make sure that they don’t make any side effects. The conditions passed to assertions may sometimes create side effects. Never put code that has to be executed as a part of the program into an assert statement.
Asserts shouldn’t be used for real error handling. Assertions check for things that should never happen.
Leave Assertions Turned On
Some people have a misunderstanding that assertions will become overhead after testing and deploying to production, and hence they should be turned off in production. The real problems start in production, not while developing or testing. Always leave the assertions turned on.
Turning off assertions when you deliver a program to production is like crossing a high wire without a net because you once made it across in practice. There's dramatic value, but it's hard to get life insurance.
- summary of Assertive Programming, from The Pragmatic Programmer: from Journeyman to Master
"This code won't be used 30 years from now, so two-digit dates are fine."
"This application will never be used abroad, so why internationalize it?"
Always avoid this kind of self-deception.
In C and C++, we have assert macros which check a boolean condition. Here is an example:
void writeString(char *string) {
assert(string != NULL);
...
}
This assert statement checks for a null string before executing the code inside the method. The execution stops when it encounters a null string.
While using assertions, make sure that they don’t make any side effects. The conditions passed to assertions may sometimes create side effects. Never put code that has to be executed as a part of the program into an assert statement.
Asserts shouldn’t be used for real error handling. Assertions check for things that should never happen.
Leave Assertions Turned On
Some people have a misunderstanding that assertions will become overhead after testing and deploying to production, and hence they should be turned off in production. The real problems start in production, not while developing or testing. Always leave the assertions turned on.
Turning off assertions when you deliver a program to production is like crossing a high wire without a net because you once made it across in practice. There's dramatic value, but it's hard to get life insurance.
- summary of Assertive Programming, from The Pragmatic Programmer: from Journeyman to Master