Refactoring in the wild
I’m please to see James Shore’s chapter on No Bugs online. It’s a great explanation of how the XP practices reinforce each other to support the development of excellent code.
One phrase in particular sticks in my mind: Technical debt breeds bugs. This reminds me strongly of the description of the Quality Plateau in the second of the original Programmers Stone talks (it’s about 2/3 of the way down the page. If you haven’t read this already, you really should). The authors — Alan Carter and Colston Sanger — move in several steps from this:
DWORD WINAPI SecondThread (LPVOID lpwThreadParm) { BOOL fDone = FALSE; DWORD dw; while (!fDone) { // Wait forever for the mutex to become signaled. dw = WaitForSingleObject(g_hMutex, INFINITE); if (dw == WAIT_OBJECT_0) { // Mutex became signalled. if (g_nIndex >= MAX_TIMES) { fDone = TRUE; } else { g_nIndex++; g_dwTimes[g_nIndex - 1] = GetTickCount(): } // Release the mutex. ReleaseMutex(g_hMutex); } else { // The mutex was abandoned. break;// Exit the while loop. } } return(0); }
to this:
DWORD SecondThread(void *ThreadParm) { while(Index < MAX_TIMES && WaitForSingleObject(Mutex, INFINITE) == WAIT_OBJECT_0) { if (Index < MAX_TIMES) Times[Index++] = GetTickCount(): ReleaseMutex(Mutex); } return(0); }
They comment:
Eleven lines vs 26. One less level of indentation, but the structure completely transparent. Two local variables eliminated. No else clauses. Absolutely no nested elses. Less places for bugs to hide. (my emphasis)
Less places for bugs to hide, less opportunity for bugs to breed. These are small-scale refactorings, and today we might make an effort to make the code even more expressive of intent, but nevertheless it’s an elegant and well-argued example of the benefits of clarity. The Stone saw the light of day in 1997 — is this the first published example of refactoring in the wild?