Copy-Paste and #include
© 21 Mar 2012 Luther Tychonievich
Licensed under Creative Commons: CC BY-NC-ND 3.0
other posts


Reuse by repetition.


The simplest kind of code reuse is a loop, which allows us to say “‍do this a lot‍” instead of saying “‍do this‍” a lot. Next comes a subroutine, which lets us name groups of actions. These aside, the simplest code re-use is the ever popular copying.

You can’t get much simpler than copying. I find where someone solved the problem I’m facing, copy their code, and dump it into my program.

Several problems arise from copying. There’s the intellectual property concerns of properly attributing everything you copy. There’s the maintenance problem of having 50 copies to fix when you find a bug. There’s the computer storage problem of having the same thing in many copies. There’s the compilation time required to handle a large file. And there’s the namespace collision when you copy a program that names something x when you also named something x for a different purpose.

Slightly better than copying is the C/C++ #include directive. When a C program says #include "someFileName" it means “‍compiler, dump a copy of someFileName here before you try compiling this file.‍” This basically resolves the intellectual property problem. It simplifies maintenance, since there is only one place to make a fix, but you still have to re-compile every program that uses the fixed code each time you fix it. Most programmers ignore the storage and compilation time issues, they not really emerging as problems until programs get very large. The main complaint I hear against #includes is namespace collisions.

Copying and #includeing are venerable techniques for code reuse and form something of a baseline approach against which others may be compared.

Looking for comments…

Loading user comment form…