1.03k likes | 1.05k Views
Defensive programming for better future. And now for something completely different …. Defensive Programming. IGNORE it, FIGHT it, MOCK it … just THINK about it!. My personal view. “Defensive Programming”. = A collection of programming techniques.
E N D
Defensive Programming IGNORE it, FIGHT it, MOCK it … just THINK about it! My personal view
“Defensive Programming” = A collection of programming techniques + A collection of stylerecommendations https://en.wikipedia.org/wiki/Defensive_programming
1. Data Checking first line of defense 2. Future Proofing never-sleeping guards 3. Readable Code help your future self
Data Checking SANITIZE THE DATA!
Data Checking SQL parameters Buffer size checking Function result checking
Future Proofing SET UP GUARDS
invariant expect precondition maintain Design by Contract guarantee postcondition http://www.elementscompiler.com/elements/oxygene/language.aspx https://en.wikipedia.org/wiki/Design_by_contract
Postcondition Precondition
Check data even when IT CANNOT BE WRONG
“Million-to-one chances ... crop up nine times out of ten.” - Terry Pratchett
“Million-to-one chances ... crop up nine times out of ten.” - Terry Pratchett
Check data even when IT CANNOT BE WRONG Especially then!
unexpected values can appear … and they will! Expect the Unexpected! case enumerations be alert when dealing with constants else ifchain
Better Unsafe!
Assert vs. raise vs. Log Will unhandled unexpected value hurt customer? Will the potential problem be caught in the develop/test cycle?
Programmers do it with TestInsight Unit Tests https://bitbucket.org/sglienke/testinsight
Unit Tests • Test error paths!
Write readable code HELP YOUR FUTURE SELF
Readable code = Maintainable code
Readable code = Maintainable code
Readable code = • Good design • Good semantics • Good formatting = global strategy = implementation details = look & understand
“A good design is like a good house – dry and solid.” “A good design is like a good house – dry and solid.” “A good design is like a good house – dry and solid.” - me Single responsibility principle Open/closed principle Liskov substitution principle Interface segregation principle Dependency inversion principle Don’t Repeat Yourself
Simpler task: What is BAD code?
“So I took little bad with a good, It ain’t all black and white …” - Iggy Pop
KevlinHenney He’s DA MAN! Look him up on YouTube!
“My <insert>, does this ever end?” deity 1769 lines!
What to do? Turn it into a class • local methods ⇒ class methods • shared variables ⇒ class fields
“We can't expect bad programmer to write good comments. We may be able to force them to use a coding style, though.” - KevlinHenney(paraphrased)