From time to time, I find myself copying a bit of code and modifying the copied version. I know very well that having two copies of the same code is a very bad idea, but those pieces of code are small and have significant differences.

The problem is, when modifying the copy, I sometimes forget some piece of the original, that shouldn't be there. So for example I first write (C# code, but that's not important here):

I have argued jokingly that copy/paste should be disabled in IDEs, but do you seriously claim that you never use it? Or even that there's never a good enough reason to?
–
pdrMay 7 '11 at 21:37

3

I must admit that this was my first response on seeing the question title, but I think a more nuanced answer is required given the actual contents of the question.
–
ChrisF♦May 7 '11 at 21:59

Typing from scratch opens you up to other kinds of bugs. In this example, the direction of the comparison in the WHERE clause changed along with the parameter name, so making it a function would be even more convoluted than a copy/paste.
–
Karl BielefeldtMay 7 '11 at 23:22

2

@Karl If you type from scratch, the "bugs" are more likely to be syntax errors. Whereas, when copying and pasting, you're more likely to forget to change something.
–
MaxpmMay 7 '11 at 23:25

In this particular example, I would tend to use search/replace to change all the DateFroms, or at least a search so it highlights all the ones I missed, but I use vim, so that kind of search is as easy as typing * when my cursor is on the word.

I agree with pdr though that unit testing is the best general solution.