Copypaste (copy-paste) is the practice of copying code fragments from one place to another without adapting them to the new context. Most often, a developer copies a block from an existing module, makes minimal edits, and pastes it into a new one — along with bugs, outdated comments, and unnecessary dependencies. According to the TIOBE Code Quality Survey (2025), projects with a high level of copypaste contain three times more defects per thousand lines of code than projects with a unified abstraction. Code duplication is the main contributor to technical debt: each copy requires separate maintenance, and fixing a bug in one place does not guarantee it is fixed in the others.
Key Takeaways
Copypaste (copy-paste programming) is moving existing code to a new place with little or no changes. The term is used pejoratively: it implies that the developer is not designing a solution but mechanically copying a ready-made block, often without fully understanding how it works.
Copypaste comes in two types: intentional and accidental. Intentional — when a developer deliberately copies code with a plan to refactor later (but the plan is often abandoned). Accidental — when duplication arises unnoticed, for example, two developers independently write the same logic for different screens.
According to the SonarQube State of Clean Code (2025) report, duplicated code accounts for an average of 12–18 percent of total code volume in commercial projects. At the same time, the cost of fixing a bug in duplicated code is 2.5 times higher than in code with a single implementation, because the developer must find and fix all copies.
The primary tool against copypaste is the DRY (Don't Repeat Yourself) principle. However, absolutizing DRY is also dangerous: sometimes copying is justified when two copies must evolve independently of each other. It is important to distinguish between "accidental duplication" (which must be eliminated) and "necessary duplication" (which must be documented).
The first and most critical danger is bug propagation. If the original code has a defect, it gets copied to all new locations along with the code. When the defect is discovered and fixed in the original module, the copies remain unfixed. The developer may not even be aware that the bug exists in five different files.
The second danger is uneven evolution. Two copies of the same algorithm accumulate different modifications over time. One copy adds boundary value validation, another changes the output format. After a few months, it becomes impossible to tell which version is "correct," and the project loses behavioral consistency.
The third danger is increased test volume. Each copypaste instance requires its own tests. If the common logic is extracted into a single function, it can be covered with one set of tests and reused. With duplication, each copy must be tested separately — this multiplies CI run time and the size of the test base that must be maintained.
The fourth danger is the illusion of productivity. Copypaste creates a false sense of speed: the developer quickly pastes the code and sees the screen working. But this "speed" turns into technical debt that must be repaid with interest when a bug is found in the duplicated block or a business logic change is required.
Understanding the reasons behind copypaste helps establish proper prevention. Most often, developers copy code not out of laziness, but because of deadline pressure, lack of knowledge, or inconvenient architecture.
The first reason is deadlines. When a screen needs to be built in two days and a similar screen already exists, the developer copies it entirely and changes only what the user sees. There is no time to refactor and extract a shared component — the client demands results. As a result, a second screen appears with 80 percent shared code but an independent history of changes.
The second reason is lack of a unified abstraction. If the project lacks a shared component for a typical task (e.g., a list screen with pull-to-refresh), each developer will write their own implementation or copy a neighboring one. Architectural decisions made at the project's start directly affect the amount of future copypaste.
The third reason is fear of breaking working code. The developer knows the existing module works. Refactoring to extract shared code may affect existing functionality. If test coverage is low, the risk of breakage outweighs the perceived benefit of refactoring, and the developer chooses the safe path — copying.
Address the causes, not the symptoms. Reducing deadlines and introducing code review will not solve the problem if the project lacks a solid architectural foundation. Invest time in creating reusable components early on — it is the only way to reduce the temptation of copypaste in the future.
Copypaste detection is performed by automated analyzers that compare code fragments and identify matches above a given threshold. The best tools operate at the AST (Abstract Syntax Tree) level and ignore formatting, variable names, and comments.
PMD CPD (Copy-Paste Detector) is the most common tool for Java, Kotlin, Swift, JavaScript, Python, and C++. CPD analyzes source code tokens and finds duplicates longer than a specified minimum number of tokens (default 100). Configuring the threshold is key to quality results: too low a threshold yields many false positives (common patterns like imports), too high a threshold misses real duplicates.
plugins {
id 'pmd'
}
pmd {
toolVersion = '7.0.0'
ruleSetFiles = files("pmd-rules.xml")
}
tasks.register('cpd') {
doLast {
exec {
workingDir = projectDir
commandLine 'cpd',
'--minimum-tokens', '75',
'--language', 'kotlin',
'--files', 'src/main/kotlin',
'--format', 'xml',
'--failOnViolation', 'true'
}
}
}
SonarQube embeds a duplicate detector directly in the Quality Gate. The Duplicated Blocks (%) rule shows the percentage of duplicated code. A threshold of 5 percent is considered healthy for commercial projects. Exceeding it blocks promotion to the release branch. SonarQube additionally groups duplicates by type: exact matches and structural copies (with renamed identifiers).
For JavaScript and TypeScript, duplicates are detected using ESLint with the eslint-plugin-sonarjs plugin (the no-duplicate-string rule) and the jscpd utility, which supports 150+ languages. jscpd is especially convenient for monorepos: it finds duplicates between packages, not just within a single module.
Refactoring copypaste boils down to one principle: extract the common part and parameterize the differences. The specific technique depends on the scope of duplication and the context.
The simplest case is duplication within a single class (e.g., two methods with the same logic but different types). The solution is to generalize with generics or reuse a method with a type parameter. If duplication spans multiple classes — extract the common code into a utility class or extension function.
A more complex case is duplication at the screen or module level. Here, simply extracting a function does not help, because the UI structure, lifecycle logic, and data binding are all duplicated. The solution is to create a common base screen class or a composite View component, and pass differences through parameters or a protocol.
// before - two copies of the same UITableViewController
class UserListController: UITableViewController {
private let viewModel = UserListViewModel()
// 40 lines of code
}
class ProductListController: UITableViewController {
private let viewModel = ProductListViewModel()
// same 40 lines but with Product instead of User
}
// after - generic base class shared
class ListViewController<T: ListViewModel>: UITableViewController {
let viewModel: T
// 40 lines of code - once only
init(viewModel: T) {
self.viewModel = viewModel
super.init(style: .plain)
}
}
The most complex case is duplication between microservices or libraries. Extracting shared code can lead to circular dependencies or unjustified coupling. In such cases, copypaste may be a conscious decision: two teams maintain independent services, and a shared library creates more problems than it solves. The key is to document such a decision and regularly check whether the copies have diverged enough to warrant unification.
Preventing copypaste is more effective than refactoring already duplicated code. The main preventive measures lie in organizing the development process, not in technology.
The first measure is code review with a focus on duplication. The review checklist should include the item: "Does this PR contain code that already exists in the project?" If the reviewer spots copypaste, they block the merge until the shared component is extracted. This requirement must be part of the team's Definition of Done.
The second measure is a shared component library. Every UI pattern that appears on two or more screens should be extracted into a common module. Create a shared module in the project and make it the mandatory entry point for all UI components. If a component does not exist — it is created first, then used on the screen.
The third measure is automation in CI/CD. Add a duplicated code check step to the pipeline (PMD CPD, jscpd, SonarQube). Exceeding the threshold results in a build failure. The developer cannot merge a PR that increases the copypaste ratio above the allowed level. This shifts responsibility from code review to automation and ensures that no duplicate goes unnoticed.
Foster a culture of "one implementation — one place." If you see an opportunity for reuse — do not put off refactoring for later. Every copypaste left "for later" multiplies and turns into unmanageable technical debt.
Frequently Asked Questions
No, there are scenarios of conscious duplication: different microservices that must evolve independently; code copied for an experiment with a deletion plan; template DTOs for different API versions. The key is to document the reason and set a check deadline for refactoring.
Copypaste is when two pieces of code do the same thing but have no shared abstraction. Healthy reuse is when the common code is extracted into a function, class, or module, and differences are parameterized. If changing logic requires edits in three or more places — that is copypaste.
PMD CPD supports Swift and Objective-C. For Xcode, there are plugins like SwiftCop and a built-in duplicate detector in AppCode. SonarQube also analyzes Swift projects, showing duplicated blocks directly in pull requests.
Create a technical ticket for refactoring each major copy. Set priorities: screens that change frequently come first, stable ones come second. For every new PR that touches duplicated code, allocate 15–20 percent of the time for gradual consolidation.
Yes, modern AI assistants (GitHub Copilot, Codeium) can analyze context and suggest extracting shared code when they detect repeating patterns. However, they do not replace automatic analyzers — use Copilot for prevention, and CPD / SonarQube for detection.
Summary
We will develop a mobile application turnkey
IT Sectr creates iOS and Android applications for startups and businesses since 2017. We will advise you and propose the best solution.
Read also