Refactor Replace Comment With Test Case

From the XpMailingList:

The notion of "Replace Comment with {test case, assertion, whatever}" has been thrown around on this mailing list. Unfortunately, it's not in RefactoringImprovingTheDesignOfExistingCode.

The general notion is this: As you read through code, you understand bits and pieces of it (hopefully correctly). You begin to stick in comments where appropriate like:

 a.doSomething(b);    /* this increments a by b */
Later on, once you've got enough comments to understand enough of the code at once, refactor out chunks of comments and create a test case that expresses in code what the non-executable comments expressed.

The reason I suggest this two-pass method is because when you're reading code, to stop and write a test case really breaks the natural "rhythm" of code-reading. Sticking in a quick comment (or, writing a line number on a piece of paper with a quick memo to yourself) doesn't have that same chop-and-change effect on your mental process (well, at least I find this to be true for me ... YourMileageMayVary).

Try it out, see if it works for you. Otherwise, find another way. ;-)

-- DossyShiobara


When I am reading code how does the test case help me understand what's going on?


Is it a good idea to replace the comments in the test cases with new test cases? :)


When I am reading code how does the test case help me understand what's going on?

The purpose of the test case is not to help you understand what's going on. I'm assuming the code reading happens in legacy code. If you write test cases after reading the code, you test the legacy code, so it's safer afterwards to refactor the legacy code (without breaking stuff). -- PeterDeBruycker

I read code all the time. Having something in a test case doesn't do me any good. Replacing a comment with a new method can often make sense, but this still doesn't document why.


Perhaps it is just the example shown (and it is a difficult job to create an example that is both easy to understand and meaningful), but I would probably just do the refactoring immediately. I consider refactorings such as renaming methods or extracting methods (without changing the extracted code!) as extremely low risk. I have usually found that these types of refactorings are necessary when trying to introduce test cases on legacy code.

I agree that one needs to create test cases before performing more aggressive refactoring and that creating test cases for legacy code must be done. I just think that using comment replacement as a justification for test cases would sound extremely weak to those I must convince to write test cases.

-- WayneMack


I usually use comments as a hint to extract method. This can be done reliably in most IDE's. Normally I don't even run my test suite after doing this. -- Ed Larmore


See RefactoringLanguage


CategoryRefactoring


EditText of this page (last edited March 20, 2006) or FindPage with title or text search