Re:The maintainability of unit tests
by jrockway on Thursday February 25, 2010 @02:02PM
(#1151293)
Refactoring and unit tests conspire to play against every inexperienced programmer's greatest fear -- deleting code. If you are dramatically changing the internal details of some code, you will have to throw away the tests that touch that internal code. You're deleting that code, after all.
Your refactor is not unguided, though, because you still have tests for the thing that consumes the unit that you are refactoring. That's how you know you didn't break anything -- the tests for the rest of your program stay the same during the refactor. (And you write new tests for the details of the code that you are changing, so that when you change something that depends on, you still have tests.)
A technique I find helpful is for classes to generally not call methods directly on objects that they old references to. Instead of calling $self->foo->bar, delegate $foo->bar to $self->bar. Then when you get rid of foo, either by refactoring, or lack of need in a subclass, you still have a bar method. Something else can provide it, or the class can provide it for itself. If you follow this rule throughout your application, classes will only be coupled to themselves; and this means that more tests survive refactoring. (Use of this technique is pretty tedious if you don't have a language feature to do the delegation automatically. I use Moose, and it makes delegation to has_a members trivial. Other languages are not so lucky.)
Your refactor is not unguided, though, because you still have tests for the thing that consumes the unit that you are refactoring. That's how you know you didn't break anything -- the tests for the rest of your program stay the same during the refactor. (And you write new tests for the details of the code that you are changing, so that when you change something that depends on, you still have tests.)
A technique I find helpful is for classes to generally not call methods directly on objects that they old references to. Instead of calling $self->foo->bar, delegate $foo->bar to $self->bar. Then when you get rid of foo, either by refactoring, or lack of need in a subclass, you still have a bar method. Something else can provide it, or the class can provide it for itself. If you follow this rule throughout your application, classes will only be coupled to themselves; and this means that more tests survive refactoring. (Use of this technique is pretty tedious if you don't have a language feature to do the delegation automatically. I use Moose, and it makes delegation to has_a members trivial. Other languages are not so lucky.)