CleanCode logo
NAVIGATION: first page in sectionprevious pageup one levelnext pagefinal page in section

Guideline RP1: Do not repeat whole functions

As trivial as it seems, it is common to duplicate a function from one file into another file. For any repeated code, maintenance is difficult at best, impractical and error-prone at worst. There is no enforcement to change all copies unless there is only one copy. And if the duplication is in separate files, it is even more difficult. Perhaps initially one developer owned two files and just copied a support function from one to the other. But later, when other developers work on one of the files, they may not even be aware that another copy exists when they change one. Depending on the language, this pitfall can have greater or lesser consequences and avoiding it requires different amounts of work.

In JavaScript, all files are loaded in a single, linear namespace. So declaring function f in one.js, and declaring it again in two.js, then loading both in an HTML file, will end up with just one copy of the function loaded. This could have unexpected or disastrous results if the function is modified in one of the files but not the other. Reading the code in one.js, one will naturally assume that the function f in the file will be executed. Likewise when reading two.js. But recall that there is only one namespace in JavaScript. So one of the copies of function f will be discarded and the code will not behave as expected. Removing the duplication, on the other hand is easy. Just delete the function f from either of the two files, leaving just a single copy of it. Both files will be able to find it, and maintenance is clean since there's only one copy of the function.

In Java, on the other hand, everything resides in a particular package. Within the package one can just refer to method m(). A different file typically will be in a different package, so it takes a bit more work to reference a single copy of a method. One must qualify the method with a package name, and access the package API via the import statement. But this small effort gains a lot by avoiding duplicate code.

In Perl, on the third hand, you can do it either way (single namespace or package namespaces). See the namespace guideline for recommendations.

Valid XHTML 1.0!Valid CSS!Get CleanCode at Fast, secure and Free Open Source software downloads
Copyright © 2001-2013 Michael Sorens • Contact usPrivacy Policy
Usage governed by Mozilla Public License 1.1 and CleanCode Courtesy License
CleanCode -- The Website for Clean DesignRevised 2013.06.30