Monday, 21 April 2014

Red, Green, and a Full 180-Degree Refactor

I have always coded first and tested later. Automated testing did not exist, and running unit tests was a manual and time-consuming process. We documented our test cases in an Excel spreadsheet and executed them manually. These were not ancient development projects from the early years of computing; I’m talking only two years ago.

I first came across TDD at university last year. It made up a small part of one lecture with a tutorial exercise to reinforce it. I loved that tutorial: getting my code to pass the tests was kind of like doing a crossword puzzle or completing a sudoku. But, to me, it was just fun. I did not appreciate the value of it.

Here at tworedkites, we have an extensive suite of test specs for each of our projects. And, like all good developers, we write our specs first before writing any code. In my haste to get started, I was not aware of this until after my first code push. What a disaster! I received an alert notifying me that I had broken no less than 527 specs. Way to get noticed on my first day!

After that, I became a spec-Nazi. Regardless of how small or purely cosmetic the change, I ran the entire test suite before pushing my code up. But I continued to also run my code manually so I could see the changes for myself. I still did not fully trust the automated testing process.

It took one more incident to get me 100% onboard: two weeks ago I made what seemed like a very simple change: a previously optional data item should now be compulsory. Making that change took me all of about 15 minutes. I manually walked myself through the process and everything behaved as expected. And then I ran the specs...

I spent the better part of a day dealing with the fallout. Those specs revealed all manner of side effects that I did not anticipate. Without them I would have fixed that one requirement and broken several other seemingly unrelated pieces.

I have learned many things during my internship at tworedkites. But the one that has had the greatest impact on me is the importance of writing specs.

Write them up front, before any code has been written. It makes you accountable. It forces you to do what you say you are going to do.

And not just any spec, it needs to be comprehensive. A comprehensive spec makes your application more robust. And because what seems unimportant or not worth testing might just be the one thing that could highlight a problem for someone else further down the line.

No comments:

Post a Comment