Today I had an interesting discussion with a colleague.I am a defensive programmer. I believe that the rule a class must ensure that its objects have a valid state when interacted with from outside the class must always be adhered to. The reason for this rule is that the class does not know who its users are and that it should predictably fail when it is interacted with in an illegal manner. In my opinion that rule applies to all classes.In the specific situation where I had a discussion today, I wrote code which validates that the arguments to my constructor are correct (e.g. an integer parameter must be > 0) and if the precondition is not met, then an exception gets thrown. My colleague on the other hand believes that such a check is redundant, because unit tests should catch any incorrect uses of the class. Additionally he believes that defensive programming validations should also be unit tested, so defensive programming adds much work and is therefore not optimal for TDD.Is it true that TDD is able to replace defensive programming? Is parameter validation (and I don't mean user input) unnecessary as a consequence? Or do the two techniques complement each other?
Does TDD make defensive programming redundant?
tdd;defensive programming
That's ridiculous. TDD forces code to pass tests and forces all code to have some tests around it.  It doesn't prevent your consumers from incorrectly calling code, nor does it magically prevent programmers missing test cases.No methodology can force users to use code correctly.There is a slight argument to be made that if you perfectly did TDD you would have caught your > 0 check in a test case, prior to implementing it, and addressed this -- probably by you adding the check. But if you did TDD, your requirement (> 0 in constructor) would first appear as a testcase that fails. Thus giving you the test after you add your check.It is also reasonable to test some of the defensive conditions (you added logic, why wouldn't you want to test something so easily testable?). I'm not sure why you seem to disagree with this.Or do the two techniques complement each other?TDD will develop the tests.  Implementing parameter validation will make them pass.