Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

I was attempting to identify an element of software engineering that I think is overlooked, not emphasized or not taught in typical undergraduate course work for CS or SE. What I came up is the concept of defensive programming. I would like to hear the community's options on defensive program and/or specific techniques that you use on a regular basis. Also, I would to know if there are any language specific techniques.

Edit:

Just to more clear. I am not looking for a lesson in defensive program. I understand what it is. I was hoping this would be more of discussion about different method members of the community employ or find valuable. Here are some techniques that I use. Keep in mind that I use C almost exclusively.

Coding standard. You not might initially think that this has anything to do with defensive programming, but it does. To illustrate, suppose your coding standard requires you to prepend variable names with the type of variable it is such as IntValue or UIntValue. The convention allows you to easily spot potential promotion rule issues like (IntX = IntValue * UIntValue)

Use preprocessor macros for constants. Personally, I think this also make your program more readable and maintainable, but it also provided a safety net. You can be sure that all areas of the code that use the macro will be updated when you change the value. Other uses of preprocessor macros can also provided defensive attributes in your code.

Some technique are built right into the language such as static variables or function declarations or in c++ data encapsulation.

Of course there are more obvious ones including validating all your input and output.

share|improve this question

closed as not constructive by Joris Timmermans, Kilian Foth, Martijn Pieters, gnat, GlenH7 May 17 '13 at 13:17

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.If this question can be reworded to fit the rules in the help center, please edit the question.

2  
joelonsoftware.com/articles/Wrong.html –  Job Jan 2 '11 at 17:08
2  
such naming convention is called System Hungarian Notation, and quite loathed in the programming community. Apps Hungarian Notation is slightly better, but the true killer is of course (in static languages such as C++) to encode this information within the type, so that code simply won't compile when it's wrong, which is about the best thing that can happen to wrong code. –  Matthieu M. Jan 2 '11 at 18:22
    
Thanks for the info. What I actually use is closer to apps, so perhaps my example was bad. I was just trying to illustrate how a convention can be used as a defensive technique. –  Pemdas Jan 2 '11 at 18:42
    
some languages don't have the notion of a pre-processor and other you can not use to set consts like you can in C/C++ –  Muad'Dib Jan 3 '11 at 5:12
add comment

3 Answers 3

up vote 7 down vote accepted

Take a look into Code Complete 2, chapter 8: "Defensive programming". For me it was the best source for this kind of technique so far. Small (~30 pages) and the main ideas are there.

Some of the main concepts strictly copied from the book, with my words (so, it may be better to just buy the book and read the original :-) ):

  • Check and sanitize your inputs;
  • Protect your routine from bad data. No "garbage in, garbage out";
  • Use assertions to document pre-conditions and post-conditions;
  • Standardize exception handling on your code;
  • Consider not using exceptions for everything - you can handle errors in another way, the programming world existed prior exceptions were invented;
  • Debugging and assertions help you during development, and most (but not all) of the debug/assertions must be disabled in production code;

But for me, the key concept lays on whether you trust or not the "other" code you are working with.

share|improve this answer
1  
Interesting, I always followed these principles instinctively because it seems like the logical way to structure (at least for paranoid programmers like myself :D), so I might check out the book. –  wildpeaks Jan 2 '11 at 14:53
2  
Use assertions to halt on impossible scenarios , not conditions that can be tested and dealt with. I almost dinged you -1 for that. Assertions are debugging tools that should be turned off in production builds. They are designed to save you time in front of a debugger, nothing more .. nothing less. –  Tim Post Jan 2 '11 at 16:31
1  
@9084 Code Complete is awesome on many levels..you won't regret picking it up. –  Pemdas Jan 2 '11 at 16:32
1  
@Tim Post, your comment makes sense to me. The problem with removing all debug and/or assertions on production code to me is that not all production enviroments are "perfect". So, if you don't have an easy deploy procedure (such as on a bank, for example), letting some debug or assertion information on production can save time solving some problems. But this is another (huge) discussion. –  Machado Jan 3 '11 at 15:56
add comment

I suppose you'll never have too many assertions in your program... Add some tight invariants to your classes, and take as granted that whatever reference/pointer you use will be null at one time or another...

share|improve this answer
1  
I've seen cases (and committed the crime myself) where the defensive checks were trying to check whether the compiler and hardware worked. OK if there's a specific known compiler or hardware bug you need to work around, or if the specific hardware is something that just generally needs some defensiveness (e.g. ECC on storage/comms) but if you're just paranoid about the compiler and machine failing, what makes you think they'll handle the defensive checks correctly? The compiler is even likely to spot at compile time that the result is always the same. Just overcomplicating the source, really. –  Steve314 Jan 2 '11 at 12:11
    
+1 for the ignoring the absurd extreme case, though. –  Steve314 Jan 2 '11 at 12:11
add comment

Parts of defensive programming very much have been incorporated into the accepted learning curricula. Defensive programming entails many different things, even though they all revolve around 'handling the unexpected'. Mainstream languages like Java and C# have explicit 'Exceptions' and 'Assertions' which come from the defensive programming philosophy. You should definitely use exceptions in your code. Assertions are more of the 'pure' defensive programming, and non-withstanding the caveats below, you should use them sparingly (outside of test code), but where appropriate.

Two other aspects of traditional defensive programming are now handled under different names. The first is simply 'Security'. I won't go into everything involved in writing secure code here.

Another is "Design By Contract". This method of programming is on the outs due to the rise of "Agile", as it's seen as too much front-loaded design. Part of the reason for that is two-fold, first, many of the previous needs to enforce contracts in imperative programming are now handled by the OOP class hierarchy such that it's impossible to get into the bad states at all, so there's no need to check them. Second, many of the traditional need to check parameters like for buffer overflows, now automatically throw exceptions by the runtime and thus needn't be checked by the coder (the runtime is checking). Finally, there is a drive, in agile, towards test-driven development, and it's sometimes impossible to generate unit tests for conditions that are not expected to happen. In such cases, a piece of defensive code will cause your code-coverage to decrease, which is a bad thing.

share|improve this answer
    
Good answer, but I would add that only coding what can be unit tested is for some types of apps the path to failure. In .net for example there are still some pretty important bits that are wrapped in close to the OS that you should handle in many situations filesystemwatcher "too many changes" behavior and most of the httpmodule events come to mind. Defensive is not contrary to Agile in all cases, but in some cases it will be and you will have to make a choice is you will write it safe or take a hit on your agile metrics. –  Bill Jan 2 '11 at 16:26
1  
"You should definitely use exceptions in your code" I don't believe that this true in all cases. I have done some code profiling of libraries implemented in c++ that use the build in exception mechanizes. The data that I used showed that using exceptions added between 25%-35% to size of the executable. This was after functionally similar error handling was added to replace the exceptions. In an embedded environment this is statistically significant. –  Pemdas Jan 2 '11 at 19:25
    
@pemdas Agreed. When writing high performance libraries, one may not want to use them. However, that's the exception. Most code is normal application code. –  Neal Tibrewala Jan 2 '11 at 22:13
    
@Pemdas, +1. Embedded environments are trully relevants these days. –  Machado Jan 3 '11 at 15:58
    
"it's sometimes impossible to generate unit tests for conditions that are not expected to happen": could you elaborate on this? If the defensive code reports invalid input your test can feed it invalid input and check that it gets an error back. Or what did you have in mind? –  Giorgio Apr 21 '12 at 14:02
show 1 more comment

Not the answer you're looking for? Browse other questions tagged or ask your own question.