Friday, December 12, 2008

Writing More Code Is Easier!?!

The statement in the title may sound like an oxymoron, but some developers I met seem to believe it.

A developer came to me one time asking me for help with a problem he struggled with for hours. The first question I asked, as I usually do: "Are the tests passing?" His response was that he was under a lot of pressure, and he had to deliver a feature very quickly for the manager. In other words, no tests were written, and the developer was planning to write them after he had verified through the web browser user-interface that the feature is fully functional.

I took a look at the code and saw that it consisted of more than 50 lines of heavy logic packed into one gigantic method. It was difficult to read and decipher, but after I got a grasp on what the developer was attempting to do, I realized that most of the logic could have been done with one line of code using one of the 3rd party libraries used heavily on the project.

I asked the developer if he thought of checking whether that feature was in the library first before writing it from scratch, and he said he was so much in a hurry, he did not want to spend the time on that kind of research.

Well, I ended up writing a test as if the method never existed (keeping with the test first philosophy,) commented the method code out, ran the test and got it failing, added a few lines of code to pass the test, wrote another test, wrote some more code including the one line needed from the 3rd party library, and voila. A method with no more than 7 lines of code was working perfectly according to the tests that specified the behavior.

So, while it may seem like writing more code is easier than doing the hard work of DRYing it up, applying design patterns, and reusing libraries that can help, more code means more code to maintain and more potential bugs to deal with. In other words, more work in the future that becomes a lot harder to deal with than writing less code that is simpler and more reliable.

1 comment:

Thomas Fletcher said...

On the other hand ... one of the important reasons that you were able to do this so effectively was that you knew that there was a library function to accomplish what was needed.

I'm not an advocate against research, but sometimes you only get to do the research in hindsight. The post-education re-factoring using tests is what is important here (IMHO).