Defensive Programming for Better Future

Slides:



Advertisements
Similar presentations
Pete Houston Maintenance, Improvement, Patch, Optimization, Errors, Bugs, …. oh I’m totally FUCKED UP! Coders tend to make many.
Advertisements

API Design CPSC 315 – Programming Studio Fall 2008 Follows Kernighan and Pike, The Practice of Programming and Joshua Bloch’s Library-Centric Software.
Software Engineering and Design Principles Chapter 1.
20 February Detailed Design Implementation. Software Engineering Elaborated Steps Concept Requirements Architecture Design Implementation Unit test Integration.
Nachos Phase 1 Code -Hints and Comments
Functions Part I (Syntax). What is a function? A function is a set of statements which is split off into a separate entity that can be used like a “new.
October, 2006 © Copyright 2006, Larry A. Beaty. Copying and distribution of this document is permitted in any medium, provided this notice is preserved.
Design - programming Cmpe 450 Fall Dynamic Analysis Software quality Design carefully from the start Simple and clean Fewer errors Finding errors.
ANU COMP2110 Software Design in 2003 Lecture 10Slide 1 COMP2110 Software Design in 2004 Lecture 12 Documenting Detailed Design How to write down detailed.
SEG 4110 – Advanced Software Design and Reengineering Topic T Introduction to Refactoring.
The Last Lecture CS 5010 Program Design Paradigms "Bootcamp" Lesson © Mitchell Wand, This work is licensed under a Creative Commons Attribution-NonCommercial.
© 2015 albert-learning.com How to talk to your boss How to talk to your boss!!
John D. Bell Polymath for Hire. Polymath?? Merriam Webster (on-line) defines it as: – A person of encyclopedic learning – From the “Greek polymathēs very.
Chapter 3 Lists, Stacks, Queues. Abstract Data Types A set of items – Just items, not data types, nothing related to programming code A set of operations.
Code Simplicity: Software Design In Open Source Projects Max Kanat-Alexander
The Birth of a Discipline
JavaScript/ App Lab Programming:
I Can Show What I Know When I Gotta Go! (…to the Bathroom)
Generics, Exceptions and Undo Command
Working with Java.
A few notes on writing a rough draft
Assessing Your Strengths
Python Let’s get started!.
Slide design: Dr. Mark L. Hornick
Handling Exceptionally Sticky Problems
Defensive Programming
Stuttering and Self Esteem
CS101 Introduction to Computing Lecture 24 Design Heuristics
Testing UW CSE 160 Winter 2017.
Storage Management.
English Proficiency Workshop
CS 5010 Program Design Paradigms "Bootcamp" Lesson 12.1
Defensive Programming for Better Future
What YOU Need to Know About Risk Management
Grades K-2 Reading High Frequency Words
Exceptions and files Taken from notes by Dr. Neil Moore
What to Do About Gossip and Rumors
UNIT I- YOUR LIFE. YOUR DREAMS
Sentinel logic, flags, break Taken from notes by Dr. Neil Moore
CSE 341: Programming Languages Section 1
Design by Contract Fall 2016 Version.
I Can Show What I Know When I Gotta Go! (…to the Bathroom)
Sentinel logic, flags, break Taken from notes by Dr. Neil Moore
Lesson 2 Programming constructs – Algorithms – Scratch – Variables Intro.
A Lesson on how to handle The Struggle.
Number and String Operations
Testing UW CSE 160 Winter 2016.
CSCE 315 – Programming Studio, Fall 2017 Tanzir Ahmed
Exceptions and files Taken from notes by Dr. Neil Moore
Writing High Performance Delphi Application
Curtis Ward, Instructor Southern Crescent Technical College
CSE 303 Concepts and Tools for Software Development
Welcome to English & Math
What YOU Need to Know About Risk Management
Beginning Style 27-Feb-19.
Body Image. Body Image Body Image Do you ever wish you could change something about your body? If so, you're not alone. Lots of people feel unhappy.
Tonga Institute of Higher Education IT 141: Information Systems
Fundamental Programming
An Introduction to Debugging
Data Structures & Algorithms
Tonga Institute of Higher Education IT 141: Information Systems
Handling Exceptionally Sticky Problems
CSE 373 Data Structures and Algorithms
Computer Science 340 Software Design & Testing
Review of Previous Lesson
Self-worth.
Solving Absolute Value Equations
What YOU Need to Know About Risk Management
Presentation transcript:

Defensive Programming for Better Future Primož Gabrijelčič

About me Primož Gabrijelčič http://primoz.gabrijelcic.org programmer, MVP, writer, blogger, consultant, speaker Blog http://thedelphigeek.com Twitter @thedelphigeek Skype gabr42 LinkedIn gabr42 GitHub gabr42 SO gabr Google+ Primož Gabrijelčič

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 + A collection of style recommendations https://en.wikipedia.org/wiki/Defensive_programming

Defense in Depth

1. Data Checking 2. Future Proofing 3. Readable Code first line of defense 2. Future Proofing never-sleeping guards 2. One never knows how specifications will change – and how some looser (probably you) will change one part of the program, but not another. Been there, done that, didn’t got a tee shirt 3. Your future help will be very grateful I know, I want a time machine just so that I can go 10 years back and give myself a lesson 3. Readable Code help your future self

Data Checking SANITIZE THE DATA! SQL parameters – not even going there. Buffer size checking – more examples later.

Function result checking Data Checking SQL parameters Buffer size checking Function result checking SQL parameters – not even going there. Buffer size checking – more examples later. Move cast() “Must be OK, I found it on StackOverflow”

Future Proofing SET UP GUARDS

Design by Contract expect precondition invariant maintain guarantee postcondition Class invarians: not going there – no nice way to support them in Delphi http://www.elementscompiler.com/elements/oxygene/language.aspx https://en.wikipedia.org/wiki/Design_by_contract

Precondition Postcondition Next: Use descriptive errors! Note: Bad use of a constant!

Use Descriptive Errors!

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! Checked: wrote that in 2009 64-bit support added in XE2, year 2012 1-in

Expect the Unexpected! unexpected values can appear … and they will! enumerations case be wary when dealing with constants else if chain

Unsafe! Better Can the compiler solve this? No, and that’s why … Can an ‘audit’ solve this? Yes, but then you must remember to run it …

Assert vs. raise vs. Log Will unhandled unexpected value hurt customer? Will the potential problem be caught in the develop/test cycle? Of course, if you can nicely exit when such problem is found, then do it, by all means.

“It is better to crash than to corrupt the data.” - me

“It is better to crash than to corrupt the data.” - me

Unit Tests Programmers do it with TestInsight In this context, Unit Tests are a future-proofing technique. https://bitbucket.org/sglienke/testinsight

Write readable code HELP YOUR FUTURE SELF

Readable code = Maintainable code

Readable code = Good design Good semantics Good formatting = global strategy = implementation details = see & understand

“A good design is like a good house – dry and solid.” - me “A good design is like a good house – dry and solid.” “A good design is like a good house – dry and solid.” Single responsibility principle Open/closed principle Liskov substitution principle Interface segregation principle Dependency inversion principle Don’t Repeat Yourself Not going there, read more about that stuff anywhere. I’m talking about my personal views today …

So … what is good code?

Simpler task: What is BAD code? It is much simpler to show bad code then to explain what makes a code good … … because it is much easier to make fun of a fellow programmer than to fix your own code.

“So I took little bad with a good, It ain’t all black and white …” - Iggy Pop

“It ain’t that bad!” (at first glance) Don’t stay long on this code example, move to next slide.

That'

Kevlin Henney He’s DA MAN! Look him up on YouTube!

https://github.com/gabr42/GpDelphiCode On github! Spend some time looking at that. https://github.com/gabr42/GpDelphiCode

“Don’t be a smartass!”

“And who will support that?” When optimization goes too far … I can definitely respect the fight for every CPU cycle, but … “Did you measure it?”

“Did you measure it?” - me

“Did you measure it?” - me

“But look, it is soooo beautiful!” At least I put a comment in so in five years when I have to fix it … I’ll just remove everything and write the code from scratch. This code is much too dense to be maintainable. Still, sometimes you have to do something for your soul, not just for the man.

“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

Style Guide Why not just write good comments? I‘ll let two great men speak …

“We can't expect bad programmer to write good comments “We can't expect bad programmer to write good comments. We may be able to force them to use a coding style, though.” - Kevlin Henney (paraphrased) Kevlin Henney

What I consider beautiful these days I’m not afraid (as I was for a long time) to let a method “breathe”. Vertical empty space inside a method is allowed You’ll still not find me writing “begin” below the “else”, that’s a pure first world waste of resources (vertical space). I do that for “implicit gotos” Exit, break, continue I do it also to break procedure into “verse” , like a poem Although that is always a sign that procedure should be split into two or more

Coding Style Suggestions

Self-documenting identifier names i, j, k: integer; i, j, k: integer; AbstractSingletonProxyFactoryBean AbstractSingletonProxyFactoryBean Name should not tell you what the entity is, but what it does. TSimpleDSLCodegen.CompileBlock SyncEdit + refactor

Long procedures are BAD Previous example should be enough … > 1 screen ⇒ bad And please don't start using 7pt point font on a 4K screen just to satisfy this rule. < 1 screen ⇒ good

Use variables to hold intermediate values

Use variables to hold intermediate values iTeletext - Example of a good variable naming (in my book).

Use variables to hold intermediate values

Use variables to hold intermediate values

Use variables to hold intermediate values

Use variables to hold intermediate values iTeletext is only used in first two lines – use an enumerator

Use variables to hold intermediate values

Use variables to hold intermediate values

Use variables to hold intermediate values MMX: Add explaining var

MMX Code Explorer is now a free tool! www.mmx-delphi.de Great thanks to Gerrit Beuze & Uwe Raabe!

Simple cases first

Simple cases first

Simple cases first

Match allocation/deallocation GetMem / FreeMem Create / Destroy If possible, keep them in the same method getmem … freemem create … destroy acquire … release Acquire / Release

Match allocation/deallocation Visually Match allocation/deallocation try … finally try..finally is cheap if there is no exception (same goes for try..except)

Match allocation/deallocation Visually Match allocation/deallocation Try .. Finally has added bonus of always releasing the FTableLock. That lock may (on exception) prevent the program from shutting down nicely.

With? Just say NO!

With? Just say NO! Is this a Component.Caption or Form.Caption? What if component ATM doesn't contain a Caption property? We actually wanted to set .Text, but as our form contins Caption, the compiler doesn't complain.

Treat numbers with suspicion

Treat numbers with suspicion Marked in the next slide …

Treat numbers with suspicion

Treat numbers with suspicion

Use FixInsight http://sourceoddity.com/fixinsight/ That was style, now we’re moving a bit up, to the architecture http://sourceoddity.com/fixinsight/

Coding Architecture Suggestions

FreeAndNil or Free? How about None? Free leaves behind a pointer to invalid memory or – worse – to some completely different data, allocated later. Use FreeAndNil.

Don’t be too smart(ass) Write the simplest possible code – you’ll be grateful in five years.

“Code CAN be a work of art – just do it at home, not at work.” - Kevlin Henney (paraphrased)

“Code CAN be a work of art – just do it at home, not at work.” - Kevlin Henney (paraphrased)

Code to the interface Long topic. Not going there. I have something else to say …

Exceptions Exceptions Danger, Will Robinson! MMX EAbort story, if time.

Can lead to a terrible design How can I know that? Can lead to a terrible design TFileStream.Create nothing EFCreateError EFOpenError Read the documentation? Who does that! Worst Delphi API! How do I know a method may read an exception? I MUST read the documentation – or the source – or »live« this in practice And what if method is changed later? Maybe by adding another exception class being raised? Who will fix all the code? Who will even notice this change? Delphi <> java where you have to announce exceptions (which then creates terribly long-winded code) so we don't know which exceptions a method may raise just by looking at method definition.

“Exceptions should NEVER cross API boundary.” - me Inside one unit, for example (even better – inside one class) I will »allow« using them. Sometimes they are great to “jump out” several levels. As far as external code is concerned, they must be replaced with Result + error property/retval.

“Exceptions should NEVER cross API boundary.” - me Inside one unit, for example (even better – inside one class) I will »allow« using them. Sometimes they are great to “jump out” several levels. As far as external code is concerned, they must be replaced with Result + error property/retval.

AcquireExceptionObject ReleaseExceptionObject

“Exceptions should NEVER cross THREAD boundary.” - me Inside one unit, for example (even better – inside one class) I will »allow« using them. Sometimes they are great to “jump out” several levels. As far as external code is concerned, they must be replaced with Result + error property/retval.

“Exceptions should NEVER cross THREAD boundary.” - me Inside one unit, for example (even better – inside one class) I will »allow« using them. Sometimes they are great to “jump out” several levels. As far as external code is concerned, they must be replaced with Result + error property/retval.

Don’t “eat” exceptions! On Error Resume Next try except end; Ignored exception =(maybe)=> wrong functioning of the program It is better to crash then to corrupt the data.

Catch them explicitly! Don’t catch ‘Exception’

Catch them explicitly!

Catch them explicitly!

Catch them explicitly! We even Catch and log all exceptions even if they are later handled in code! Except exceptions which are handled explicitly. Example: with AutoLog.Expect(ERestRequestException) do try try actionRes := method.Invoke(Self, arguments); except on E: ERestRequestException do overrideResult := TRestResponse.Create(E.RestResponse); end;

Our practice Catch and log ALL exceptions Even HANDLED Unless they are announced in a special way Totally not saying you have to do that! Why? Because of various legacy code that is (was) eating exceptions.

Our practice Totally not saying you have to do that! Why? Because of various legacy code that is (was) eating exceptions. WITH in this case is just a formatting tool, except that it is not …

Use exception logger EurekaLog madExcept JclDebug

Wrapping up WHAT TO REMEMBER? When I looked over my code for the last 20 years, I found out that I have something entirely different to say …

Don’t write the same code over and over.

Don’t write the same code over and over. Try something new. Experiment. Learn. Make mistakes. "You learn nothing if you get it right in the first try"

Don’t write the same code over and over. Try something new. Experiment. Learn. Make mistakes. Evolve.

A human being should be able to change a diaper, plan an invasion, butcher a hog, conn a ship, design a building, write a sonnet, balance accounts, build a wall, set a bone, comfort the dying, take orders, give orders, cooperate, act alone, solve equations, analyze a new problem, pitch manure, program a computer, cook a tasty meal, fight efficiently, die gallantly. Specialization is for insects. -Robert A. Heinlein