Basic defensive programming [duplicate]

2019-07-19 15:17发布

问题:

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:

Have a look at

  • Defensive programming
  • Case Study – Defensive Programming
  • The art of defensive programming

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.



回答2:

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 ;).



回答3:

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


回答4:

http://en.wikipedia.org/wiki/Defensive_programming

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)