On 31/01/06, Russel Winder <[EMAIL PROTECTED]> wrote:
> On a mail list I am on there has recently been a huge debate raging on
> "defensive programming" and the fact that it is a bad thing in these
> days of test-driven programming.  An (arguably trivial) example of one
> of the many issues:
>
> In a for loop people are taught to write things like:
>
>         for ( int i = 0 ; i < N ; ++i ) { . . . }
>
> instead of:
>
>         for ( int i = 0 ; i != N ; ++i ) { . . . }
>

<snip>

This isn't an answer to your question, and not terribly relevant, but
I think there are a couple of fallacies here. One is that we're
writing code to be executed, rather than read. The i<N idiom is, I
think, somewhat easier to read (once you've understood it) because it
implies that we're iterating over a subset of the positive integers
less than N, in fact you can probably look at that part of the
declaration and guess what the rest might be. I tend to think that
i<>N is a little more ambiguous.

As for defensive programming vs. unit testing I generally try to write
tests to see if defenses like this are working properly, perhaps I'm
just a pessimist. However, if all or most of the possible error
conditions associated with a piece of code are expressed in the unit
tests and aren't made clear in code then surely you need to read both
to properly understand the intended semantics of the program? This
seems worse rather than better to me, and it's pretty much what the
aspects people are doing -- taking the semantics of one thing and
splitting it into several pieces.
Much nicer is design by contract where everything's done in-code,
although that's not really the same sort of thing as unit testing.

As for teaching there always seems to be a big push to discard
anything that's too "hard" to teach rather than, say, to teach better.
There is some mileage in this where programming is concerned because
it is *so* hard to learn, but if we only teach the easy stuff we're
doing ourselves out of a job! The i<N idiom might be harder to learn
at first, but once you've "got it" you've probably understood
something much deeper about iteration than if you over-specialise your
termination conditions.

Cheers,

Sarah

--
http://www.mis.coventry.ac.uk/research/imd/
http://varspool.blogspot.com

----------------------------------------------------------------------
PPIG Discuss List (discuss@ppig.org)
Discuss admin: http://limitlessmail.net/mailman/listinfo/discuss
Announce admin: http://limitlessmail.net/mailman/listinfo/announce
PPIG Discuss archive: http://www.mail-archive.com/discuss%40ppig.org/

Reply via email to