Monday, October 25, 2010

TDD: What's the Point?

What's the point of TDD?  This might sound outrageous, but IMHO, the point of TDD is not to exhaustively test your code as your developing it.  It's not to test every corner case, every possible input/output scenario imaginable.  It's not even -- gulp -- to achieve 100% code coverage. 

What?!  Blasphemy! 

Yeah, yeah.  100% coverage is a worthy goal, and if you're doing TDD right, you'll get pretty close anyway.  But still, 100% coverage isn't the point.

The point of TDD is to force you to design and write your code from an outside-in perspective, rather than an inside-out. It therefore also ensures that it is testable, well modularized, free of inappropriate foreign entanglements, and is most likely to work the way you need it to.  The focus is on the use of the class, not the implementation of the class. 

When you're not doing TDD, you're thinking more (sometimes exclusively) about what the class needs, and how it will do what it will do.  When you do TDD, you think more about how the class is used, what it's user's need, and what the rules are.

You write better code that way.  So TDD is a way of getting yourself to write better code.

So TDD is an approach to development -- not an additional task added to development.  It isn't overhead.  That brings me to the next topic.

Wednesday, October 13, 2010

Sabotage Your Code with Time Bombs

Sometimes you need some code for a short period of time, after which
it needs to be removed.  I've been having to do that a lot in the past
few weeks.  If I'm an average developer, then the average developer
has, at one time or another, done this by putting in comments like:

// XXX HACK FIXME TODO remove this!!!

The problem with this is you write it and then forget about it.  It
gets lost in the bazillions of other auto-generated TODO comments.
Granted, an above average developer doesn't tolerate all those
auto-generated TODO comments.  But then, by definition, most of the
developers in the world are average.  Like me.

The point is, it gets forgotten, and many times you never go back to
make the fix.  Well in a case I ran into this week, I had to be
absolutely certain that this time, it couldn't slip through the
cracks.

The solution?  TimeBomb.

It looks like this:

TimeBomb.explodeAt(11, 1, 2010, "Remove the following line or else...");

The explodeAt method checks the current system date, and if it's past
the date you've given it, will throw a java.lang.RuntimeException with
the message you provide in the last argument.

It's easy to ignore a TODO comment. Not so easy to ignore a broken app.

Oh, and I'm not showing the implementation, because if you can't
implement that, then you aren't (or shouldn't be) writing Java code to
begin with.