Writing the simplest code to make your test pass
I realized with my last bit of coding/post that i was following one of the rules that jay had told me about: “Once you've written the tests, provide the simplest implementation that makes them pass”. However, when writing a library it's a little unclear what that means. Do i provide the simplest implementation of an ArrayCollection that makes this pass? Or do i just provide the simplest implementation of an ICollection that makes this pass. In either case I didn't do that. The simplest implementation i think i could come up with would be to do:
class Collection<A> : ICollection<A>
{
bool empty = true;
#region ICollection<A> Members
public bool Add(A element) {
empty = false;
return true;
}
public bool Empty {
get {
return empty;
}
}
#endregion
}
Part of me cringes at this. But for the life of me, the more i think about it, the more I like it. If my interface only allowed me to observe the state of the collection through “Empty” and it only allowed me to affect that state through “Add” then this really is the simplest implementation. Why did i build up that A[]/count state in the earlier example? They overly complicated things and they required me to implement a complex algorithm with many areas for error.
Of course, this implementation wouldn't scale when i started adding more methods and invariants on the interface. But i think i should do the fixing up then rather than now.
Comments
- Anonymous
May 17, 2004
Actually, the rule is to commit whatever sins are necessary to get the test to pass as qucikly as possible, and then refactor to remove duplication. (Duplication between the test and the production code should be removed, too.)
When you start, your first test will probably check that a newly created collection is empty. In that case, the Empty implementation will be "return true;". Then you have duplication between the 'true' in the impl. and the 'Assert()' in the test, which you can choose to refactor now or later.
But it does look like you're on the right track. Wait until you have the later tests to motivate the code changes you know you want to do to the class.