Pairing Lessons #1: Be cynical with code
by Chris Wash on Feb.10, 2010, under Uncategorized
The following scenario plays out a lot when I pair up with people, so I thought I’d distill it down and write it up for future reference. I think teaching lessons through scenarios could make for an interesting series of articles, and I’m sure others have equally interesting experiences to share.
I’ve tried to condense this down to just the steps vital to understanding the underlying problem (though this is certainly not the only way to get there) and introduce some terminology (providing links, even if deferring to google) along the way. I hope these help out aspiring or new developers.
Here’s a scenario: you find yourself doing X all over the place, (where X is nearly anything) and you’re just plain tired of writing the code to do it. You first reluctantly copy and paste it into new places, and twiddle what you need to twiddle to get it to work. You soon realize this is a pain because it’s error prone – you can mess things up using copy and paste. You fancy yourself the pragmatic type and decide to write a IDE template that will fill in the code for you instead of having to write it out every time.
(Aside: This is but one of many kinds of code generation).
If you are using code generation, you stopped asking “why” too soon. -mahvne
This helps with the problem of introducing errors, but you soon you realize this code is everywhere, cluttering up other code. Not only that, when the structure of this code changes a little bit, you need to go and change it everywhere it was copied and pasted, or generated using your template.
(Aside: It’s a violation of the DRY principle.)
Now you decide the best course of action is to try get this code to a common place that’s visible across every part of your project. You also have to go find every place you copied and pasted or used your template and replace them with calls to your method that use generic parameters.
(Aside: You’ve just created a static utility method.)
You make up your mind that in the future, it will be much easier to do this before the code gets copied and pasted that many times, and vow to follow the three-strike rule of refactoring.
(Aside: And use automated extract method refactoring and move method refactoring to do this).
The lesson to take away is this: any line of code you introduce creates change points and increases complexity. We need to make sure the lines of code allow into our code base are well-factored/designed/tested and worthy of our ongoing maintenance efforts. Really – try to break your code before it leaves your hands. Fix it, or get rid of it. While this might seem cynical at first, you’ll understand it’s just preventative maintenance, or programming deliberately (not programming by coincidence).
