semantic-clone

Code with the same behavior appears in more than one place.

Group
Code
Runs
On by default
Level
warning
Reads
Every file
Fix
--fix fixes it: each later copy of a top-level Python or JavaScript function in the same file calls the first

Why

These pieces of code compute the same result with the same effects, even where the syntax differs. Keep one and call it from the others. Each finding lists the language assumptions the comparison relied on.

The fix, as Ur suggests it: keep one copy and call it from the other places.

For agents

Before writing a function, look for one that already computes the same result and call it instead of writing another.

Example

src/cart.js
export function subtotal(items) {
  let sum = 0;
  for (let i = 0; i < items.length; i++) {
    sum += items[i].price * items[i].quantity;
  }
  return sum;
}
src/invoice.js
export function lineTotal(lines) {
  let total = 0;
  for (const line of lines) {
    total = total + line.quantity * line.price;
  }
  return total;
}
What Ur prints
$ ur lint --rule semantic-clone
warning[semantic-clone]: 2 functions have the same behavior
  --> ./src/cart.js:1:8-7 function `subtotal`
  --> ./src/invoice.js:1:8-7 function `lineTotal`
  = assumes: dense-arrays, pure-operators
  = hint: keep one copy and call it from the other places
  = see: A Survey on Software Clone Detection Research, Chanchal K. Roy and James R. Cordy, Queen's University technical report 2007-541 (2007-09), http://research.cs.queensu.ca/TechReports/Reports/2007-541.pdf
1 clone class in 2 files

Try it in the playground →

Source

A Survey on Software Clone Detection Research, Chanchal K. Roy and James R. Cordy, Queen's University technical report 2007-541 (2007-09).