2

I've always thought defensive programming was evil (and I still do), because typically defensive programming in my experience has always involved some sort of unreasonable sacrifices based on unpredictable outcomes. For example, I've seen a lot of people try to code defensively against their own co-workers. They'll do things "just in case" the code changes in some way later on. They end up sacrificing performance in some way, or they'll resort to some silver bullet for all circumstances.

This specific coding practice, does it count as defensive programming? If not, what would this practice be called?

Wikipedia defines defensive programming as a guard for unpredictable usage of the software, but does not indicate defensive programming strategies for code integrity against other programmers, so I'm not sure if it applies, nor what this is called.

Basically I want to be able to argue with the people that do this and tell them what they are doing is wrong, in a professional way. I want to be able to objectively argue against this because it does more harm than good.

void.pointer
  • 24,859
  • 31
  • 132
  • 243
  • Perform Code Reviews and have an agreed upon coding standard .... – Mitch Wheat Feb 05 '12 at 04:28
  • Making your code work even when other components change, I believe, is called "Dependency Injection", falling under the umbrella term "Modularization", and is a great idea. –  Feb 05 '12 at 04:47
  • 1
    If you are coding defensively against their own co-workers, the problem will not be solved by writing code. I would suggest calling a meeting. :) – Christian Neverdal Feb 05 '12 at 05:03

2 Answers2

2

"Overengineering" is wrong.

"Defensive Programming" is Good.

It takes wisdom, experience ... and maybe a standing policy of frequent code reviews ... to tell the difference.

paulsm4
  • 114,292
  • 17
  • 138
  • 190
  • 4
    PS: I'd consider "checking return values" and "validating input" as "defensive coding". I'd consider "globbing on extra code just on the off chance my co-worker might someday change his code" as stupid and unproductive. – paulsm4 Feb 05 '12 at 04:36
1

It all depends on the specifics. If you're developing software for other programmers to reuse, it makes sense to do at least a little defensive programming. For instance, you can document requirements about input all you want, but sometimes you need to test that the input actually conforms to the requirements to avoid disastrous behavior (e.g., destroying a data base). This usually involves a (trivial) performance hit.

On the other hand, defensiveness can be way overdone. Perhaps that is what's informing your view. A specific example or two would help distinguish what's going on.

Ted Hopp
  • 232,168
  • 48
  • 399
  • 521