How Code Duplication Affects Program Modification

Duplicating code (say, by copying and pasting with a text editor) has much more far-reaching consequences than you might imagine.

Programs are constantly being modified. In fact, after an initial start, all of the development that you do is program modification.

Suppose that you duplicate a section of code S (with minor changes). You might manage to get the program working to begin with. But then, what if you need to modify S? Will you remember to modify every copy of S in the program? Experience shows that you probably will forget to modify all of the copies of S. That is true for experts as well as beginners.

Not only do you need to put in a lot of time trying to find all of the copies of S, but you probably end up with an inconsistent program that does not do S in the correct way in some places.

For those reasons, duplicating code is considered poor practice. You avoid it by writing the code once, in the body of a function. Each place where you want to use that code, call the function.