views:

265

answers:

4

Possible Duplicate:
Favorite (Clever) Defensive Programming Best Practices

I am always advised by some programmers to pay concentration to easy debugging. What is defensive programming and to which extend should it be considered while practicing?

And one more important question: is there any key things to consider while coding and what are they?

+1  A: 

http://en.wikipedia.org/wiki/Defensive%5Fprogramming

Defensive programming means, that you check if a file exists and if you have the permissions to open it instead of just trying to open it and catching any eventual exceptions. (Just an example)

eWolf
That is a spectacularly bad example, as files are system-wide resources and any checks you make can be made irrelevant by the time you open the file.
Pete Kirkham
I'd argue that "defensive programming" in this case would be to actually remember that IO can fail, and to catch the exception, and dealing with it in a sane manner. (as opposed to waiting for it to happen and backfitting the error handling)
Daniel Bruce
@eWolf: Well, I would not call that defensive programming. Defensive programming is more about things that should be true, because provided by other part of the program, that you check nonetheless. @Daniel: Things that may fail because you call external ressource should be checked in any case defensive programming or not. Checking before accessing a file or such is not enough. You must check also result of real access, because something can happen between first check and real access that can raise error condition.
kriss
@Pete: I did not say that you could forgo the Try-Catch, neither did I say that these checks were a good idea.@Daniel: You should always put IO, database, network or similar code in a Try-Catch, shouldn't you?
eWolf
+3  A: 

Have a look at

Defensive programming is the idea that the developer makes as few assumptions as absolutely necessary. In addition, the developer preemptively creates code that anticipates not only potential problems but also specification changes.

astander
+2  A: 

As a rule of thumb -- if you catch yourself thinking "this will always be true", write ASSERT( condition) in that place. That is probably the core of what defensive programming should be ;).

Kornel Kisielewicz
+2  A: 

If defensive programming meant only one thing , that should be use assert extensively.

Here is a good article about when and where to use assert.

There are many situations where it is good to use assertions. This section covers some of them:

* Internal Invariants
* Control-Flow Invariants
* Preconditions, Postconditions, and Class Invariants
pierr