The Two Kinds of Defensive Programming
May 14, 2009 10:21

I made a few points in last week's presentation on which I want to expand a bit. One of them is about "Defensive Programming"

There are two kinds of defensive programming - the good kind and the common 'flinchy' kind.

I learned about the Good kind of defensive programming in the changed-my-life book The Pragmatic Programmer. The key concept in defensive programming is to assume Murphy's Law is going to happen to your application, and write your code to be able to handle it. A few techniques I often practice are:

  • Asserting that proper values have been passed to any important or complex methods
  • Double-checking that the current user has proper access to the objects and elements being worked with
  • Being smart about when to break out repeated code into functions, objects, and methods (which sometimes means I don't)
  • Using delegates and the Law of Demeter to hide composition and implementation details
  • Having sensible defaults to 0 or '' for missing data, unless there's a good reason otherwise
There are many other aspects to defensive programming that can be found in The Wikipedia Article.

                    But there's a much more common kind of defensive programming: the kind done by scared programmers.  I sometimes call it 'flinchy programming'.  They're inexperienced, they don't know the language or the framework very well, the application they've been assigned to work on is messy and complex, and they're likely to be in an unhealthy authoritarian work environment with an overbearing boss.  

It's fairly common that when a project starts to collapse, the good programmers shy away from it, or management decides that it's not worth wasting good resources on it anymore - so more junior staff get assigned to it, who are out of their depth and on bad project schedules.

Usually, 'flinchy' defensive code is written very quickly, with no regard for reliability, maintainability, or legibility. The only thing on a defensive programmer's mind is to get it working 'well enough to not get fired'.

                    Common techniques in the bad kind of defensive programming include<ul><li>copying-and-pasting rather than building a function or a method, since "there's no time for thinking about it!"</li><li>writing their own custom string or array management methods instead of using existing ones already in the language, framework, or application, since "I can't go through all of that documentation!"</li><li>if existing functionality isn't working properly, working around it instead of fixing it</li><li>blindly using code generators or wizards to build functionality that they don't understand</li></ul>We've all written our share of 'flinchy' code - I certainly have - and usually it has been written at 3 in the morning right before some arbitrary deadline.  Some people, however, <em>only</em> write this way.

                    'Flinchy' defensive code is often easy to fix - the difficulty is in figuring out what they were trying to do in the first place.  On the Careerious rewrite, a junior C# programmer had to implement a piece of PDF report code that displayed three paragraphs based on 9 criteria, so he copied-and-pasted the same 15 lines of code <strong>27 times</strong> and changed the number reference in each case.  I simply wrote a separate method, which took the passed number reference, and I called it from a loop that went through an array of the appropriate values.

                    'Flinchy' defensive programmers are often harder to fix.  The key - especially if you find yourself doing it - is to slow down and relax.  Athletes and writers and martial artists and musicians have all learned that you can't perform at your best if you're jumpy and nervous: there's power and strength in relaxation.  Take ten deep slow breaths, go for a walk, or have a glass of water.  Then look at your code again and see if you can work smarter instead of harder.

                    <embed src="http://blip.tv/play/AYGA9gSUhVo" type="application/x-shockwave-flash" width="640" height="390" allowscriptaccess="always" allowfullscreen="true"></embed> 
Other Blog Posts
Finding Burgers Fast: My DIY Halifax Burger Week Site "This is Nowhere" at PodCamp Halifax 2018 The Diary Diaries: Fixing Remembary's Facebook Connection Special Leap Day Edition of "Some Weird Things About Time" What's Up With Remembary Can't get pg_dump To Work Now That Heroku Has Upgraded Postgresql to 9.4? The Best Thing I Ever Did To Promote My App If You Build It, They WON'T Come #deployaday, My Big Hairy Plan for 2015 Extracting Plain Text from an NSAttributedString My Year of "Hits" Part 2: Remembary Rolling My Year of "Hits" Part 1: Remembary Rises (and Stumbles) Handy Little Test Method to Check for Translations in Rails Apps My Suddenly Slow-Waking MacBook Air Indie App PR: Keeping Control of Your Tone A Quick Note on 'clone' in Rails 3.2 My eBook Apps 2: iOS, JavaScript, and Ruby My eBook Apps 1: Introduction Quick Tip: No Sound on Mountain Lion My Upcoming Talk at PodcampHFX 2012: My Year of "Hits" starshipsstarthere.ca: Building at the Speed of Funny Screencast Tips Remembary's Cool New Picture Support Indie App PR 2: Keeping On Top Of User Feedback Indie App PR 1: How to Handle an App Disaster Giles Bowkett Diary Project 2 Remembary Video Congratulations! Welcome to Your Nightmare! How My iPad App Remembary Took Off Why You Should Have an App in the App Store (Even If You Probably Won't Make Any Money) PodCampHFX Remembary Presentation - Part 3 How I Used MailChimp Autoresponders to Promote Remembary PodCampHFX Remembary Presentation Part 2 PodCampHFX Remembary Presentation Part 1 Why AdWords Ads Don't Work for iPad Apps Remembary is Sponsoring PodcampHFX Why Can't I Resize my Views in Interface Builder? Momento and Remembary Concerning Remembary iPad-Friendly eBooks of Gracian's Art of Worldly Wisdom Project Report: PTOS2 A Quick Note on Encryption We're all LUsers Thoughts on HAML Friday Afternoon Hack - Getting Beyond the Basics Halifax Friday Hack and Back to Basics Quote from Wil Shipley FutureRuby Make Web Not War Busy Week I: Toronto Ruby Job Fair Employment.nil - the Toronto Ruby Job Fair Code Count: Ruby on Rails vs. C#/ASP.NET A Brief Note on Twitter The Hub Halifax and Mobile Tech for Social Change Deep Thoughts on Microsoft From The Accordion Guy The Two Kinds of Defensive Programming Presentation - Fixing Careerious: From C#/.NET to Ruby on Rails Enterprise! Presenting at Ruby on Rails Project Night - May 7th New Name and New Look for Careerious/Clearfit FutureRuby and More From Unspace Health Tips for Programmers This tables meme won't die Careerious - Ruby and Rails vs. C#/.NET Yeah I Use Tables For Layout, So Sue Me The Different Kinds of Done Giles Bowkett's RubyFringe presentation OfficeTime: Great Time-Tracking App for OS X Back With A New Look Non-DRY Feed torontorb Keeping Your Sanity With The Command Design Pattern shindigital Is All Grown Up! (according to the spambots) Startup Stars? I'm so bored! The Magic Words for RMagick Jennifer from Operations You see? Naming is HARD Business Software as Process Documentation Deployment note: 'execve failed' Steve Jobs on Market Research Why Canada Is Better for Entrepreneurs "Program first and blog second" Toronto Tech Collage The MacBook Air Is A Roadster RubyFringe! Quote of the Week: Steve Yegge Starting Up: Cards Great design tool: browsershots.org Starting Up: The Logo Quotes Of The Day: Hedge Fund Interview TSOT Ruby / Rails Presentation Night - Part 1 Moneyworks: Accounting Software for Canadians on OS X Starting Up: The Name Nice logo, but why is your site so bland? Welcome to shindigital.com