Defensive programming — Code Craft

Defensive programming, what is it ?

  • You save a lot of your debugging time! Indeed, when you work with good code, you are rapidly notified if you are using it badly, which will help you debug your program much faster than if the code give you no clue.
  • Your code will be more persistent, more robust through time. Once written, good code will have less chance to find a bug in it, or to rewrite it in case of modification in the specifications of the software. 💪
  • You will have to do more work upfront. Indeed, writing good code require that you spend more time than writing only correct code. But this is time that you, or someone else won’t spend on debugging the code you’ve written 😉
  • The code will consume more resources. And this is something than can be huge depending on your project. Indeed, one check call one time won’t be much, but several checks call many thousands of times, or even more, can really slow your program. There are some techniques that can be used to minimize that problem (for example, removing automatically the checks when creating a release, and nor during the debug), so don’t worry too much about this one.

General Techniques/Rules for Defensive Programming

Guard against what ? and where ?

  • Pre-condition, which are the conditions that must always be true at the beginning of a function, before the code of the function, like input validity.
  • Post-condition, which are the condition that must always be true at the end of a function, after all the code of the function, to guard against error in the function code.
  • Invariant, which are conditions that are always true at some point in the program execution, and which validate the program logic
  • Assertion, which are all the other check of the program state at any given point in time.

Offensive programming

Conclusion

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store