From: Pat Maddox Date: 2006-03-06T08:48:55+09:00 Subject: Re: asserting in code vs unit tests On 3/5/06, chiaro scuro wrote: > On 3/6/06, E. Saynatkari wrote: > > Or, instead, you could in many circumstances ascertain that the > > method that produces the input does not produce negative numbers; > > this is something that a unit test would do and it would eliminate > > the need of a constraint :) > > We are on something interesting here. I am tempted to agree with you, > but for the sake of discussion and to explore the idea with you I will > say: > > * a test doesn't prove that it will never produce a negative number, > it simply checks that it doesn't do it under certain very specific > conditions > * a postcondition will always check that it doesn't produce a > negative number and it will warn you if it does. > > In this sense pre and post conditions seems to serve different purposes. > > the precondition defines a scope of valid input and checks that that > input is well formed. > tests check a method, passing it valid input and expecting a 'specific' result. > a postcondition defines a scope of valid output and checks that the > output is well formed. > > pre/post alone are not enough because they just check the domain of variables. > > you need tests to verify that at least under some conditions the > method yields meaningful results. > > tests alone however are never exhaustive and cannot prove correctness. > assertions can catch some types of 'wrongness'. Isn't that what exceptions are for? def foo(a) raise 'Argument can not be negative' if a < 0 b = something_that_should_always_be_positive raise 'Something strange happened and b was negative' if b < 0 b end foo expects a to be positive, so when a negative number comes in that's an exceptional case. It also should always return a positive number, so if b is negative then something really went wrong and it should terminate. Pat