Was writing some code the other day, and then wanted to have similar functionality in a different area of the codebase. I did not want to directly copy and paste, as I consider this to be a very recognizable code smell. Basically, copying and pasting is a clear indicator that there is similar structure that is not being realized. It is similar to making up really complicated equations and models for why planets in the sky do loop-de-loops, and then understanding that they all revolve around the sun. That understanding simplifies things.
However, it was tough to think about what needed to be abstracted out of the solution that I was going to use. What I did was to copy the original to another area, change it to work in that context, and then factor out the common parts as best as possible to a library function. I expect to use this function a few times, so this seems to make the most sense from a flexibility and maintenance perspective.
Copying allowed me to clearly see the similarities and the differences so that I knew where the seams were. Just doing it in my head was not as helpful. I was overthinking it, and came up with a couple of solutions at first that were suboptimal. Then, I said, “whatever, just get it done and I can refactor from there.” That seemed to be a better solution. Also, I felt that I did not overgeneralize the functions when I used this approach. This is a positive, as when I overgeneralize, the code becomes harder to work with in the future.
Note that I did indeed go back and reduce the duplication. :) Pushing it out to a nebulous “sometime” would have been quite ineffective. Instead, I promised myself “in half an hour.” I felt good about keeping this promise to myself.
I guess the lesson I learned was: use the materials you have to help you on your way. Whether this is temporary image files when you are preparing your website overhaul, or scraps of paper or whiteboard space, getting ideas out in physical form lessens the load on your mind. See also my post on streaming, which I still use on a daily basis.
Do you have any rules of thumb for this type of situation?