In my previous posting, I suggested that “scavenging, borrowing, and blatantly copy code” is the staple of modern software development; this is, of course, true. However, there are caveats to consider, both legal and technical.
Legally, you need to be aware of the license that governs the code you’re copying. If the license permits it, you’re good-to-go. In some cases, the license may ask for attribution; that is, the license may require that you include a comment in your code that indicates where you got it from and who owns the original work. Pay heed to the wording of the license, because there may be restrictions or requirements on "derivative works" (e.g. you may be legally obligated to release your derivative work under the same license).
From a technical point-of-view, wholesale duplication of code is something to avoid. I remember a demo for a new product I attended many years ago in which the demonstrator was showing us how easy the product was to extend. "All you have to do is copy this 800-line long method and change these two lines at the end. See how easy it is?". The presenter missed an important point. What happens when those original 800 lines get updated? By copying all that code, they had worked themselves into a dangerous support position. What might previously have been a single branch of code became two separate but mostly identical branches that both need to be maintained (i.e. when the original changes, so must the copy). And who knows… over time more branches might be added, amplifying the developing support nightmare. The moral is that wholesale duplication is rarely good.
As a general rule, if you find that you need to copy lots of code, then chances are a better solution might be to refactor the existing code to make it more easily extended. And chances are that before you refactor, you may be able to find another way do what you need to do without duplication (refactoring existing code is not always possible; check the license).
So what kind of copying is good? In my previous posting, I was attempting to allude to copying idioms out of existing code. Recently, I needed to build a table in SWT and couldn’t remember how to do it (my brain capacity is too limited for me to memorize such things). I used the search capabilities in Eclipse to find code that builds a table using
org.eclipse.jface.viewers.TableViewer as a starting point (I do remember some things). After about a minute, I found an appropriate example, copied it, and changed it to do what I needed. In the end, the original code is barely recognizable.
For most of the code in Eclipse, this sort of copying is okay. However, at the end of the day, it’s always best to review the license before you copy.