Search⌘ K
AI Features

Combine Duplication

Explore how to detect and refactor duplication of fact, logic, and structure in Rails models through test-driven development. Understand practical methods like using constants, instance methods, and encapsulating logic to write cleaner, more maintainable code with custom RSpec matchers.

We need to look out for three kinds of duplication:

  1. Duplication of fact

  2. Duplication of logic

  3. Duplication of structure

Duplication of fact

Duplication of fact is usually easy to see and fix. A common case is a “magic number” used by multiple parts of the code, such as a conversion factor or a maximum value. We saw this in an earlier example with the 21 days we used to calculate velocity. Another common example is a status variable that has only a few valid values, and the list of those values is duplicated:

Ruby
validates :size, numerically: {less_than_or_equal_to: 5}
def possible_sizes
(1 .. 5)
end

The remedy for duplication ...