Take error handling really seriously. A program that can gracefully reject input with a detailed error message is far better than one that crashes mysteriously
Take error handling really seriously. A program that can gracefully reject input with a detailed error message is far better than one that crashes mysteriously
1. Re-structure your logic so the error cannot happen
2. If you can't do 1, recover from the error silently and continue on with the program
3. If you can't do 2, handle the error gracefully and notify the user of what state is changed, letting them choose whether or not to continue
4. If you can't do 3, inform the user of what happened and ideally provide the user corrective action they can take, then exit cleanly with an error code
5. If you can't do 4, exit cleanly with as descriptive of an error code as you can
6. If you can't do 5, you're probably faced with crashing or exiting with some unhandled exception. This is a bug that should never go into production.
Always be looking for opportunities to move your code up that hierarchy. Moving every 6 to 5 is my personal bar for barely acceptable quality. 4->3 is usually a big win (basically anything that prevents the program from exiting).
I think that defensive programming is the worst way of dealing with errors. You are now silently diverging from your business requirements by making up data.
That attitude hurts everyone who has to support what you write.
edit: Reformatted as a habit "Make sure whatever you write can be supported without unnecessary headaches."
Assertions, however, are great. If you can force the program to throw that NPE closer to the point where it actually illegitimately became null, the debugging session becomes much shorter. Null-safety in the type system (like with most modern languages: Swift, Haskell, Kotlin, Scala, Rust, etc.) is even better.
And: Using a different language is always a great idea, but often not possible.
Code should tolerate all sorts of bad inputs. Code should produce pristine outputs.
Just like being a model member of society
Googled and found it:
https://en.wikipedia.org/wiki/Robustness_principle
https://en.wikipedia.org/wiki/Jon_Postel
"In his lifetime he was known as the "god[2] of the Internet" for his comprehensive influence on the medium."