Friday, May 4, 2012

Copy/paste of code is not ok

Much too often, I see patches that add code copied from other sections of the same repository. The usual excuse is that, well, we know that block of code works, it's easy to copy and we immediately get the result we need.

This is rather short-sighted. Whenever code is copied, the two instances will go and live separate lives. Code is never static, over time that copy becomes a partial reimplementation of the original.

There are a few conditions when copy-paste is acceptable:

  • You can guarantee that the original code does not have any bugs and thus the copy does not have any bugs, now or in the future. Otehr

  • You can guarantee that anyone making changes to this code in the future is aware of the copy and the original and their respective contexts.

  • You can guarantee that the context of the original and the copy never changes in a different manner.

  • You are happy to reimburse testers and developers for the time wasted tracking down bugs caused by ignoring any of the three above.
If the above are true, copying code is ok. And you probably get some price for having found an impossible piece of code. In all other cases, write a helper function and share the code. If the helper function is to unwieldy, maybe it's time to think about the design and refactor some things.

No comments: