Sobes.tech
Junior — Middle

Can you explain the principle by which code should not be repeated in different parts of the project?

sobes.tech AI

Answer from AI

The principle that code should not be repeated is called DRY (Don't Repeat Yourself). It means that each piece of knowledge or logic should be represented in the project only once.

Repeating code leads to:

  • Increased code size and maintenance complexity.
  • Risk of errors during changes (need to fix in multiple places).

To adhere to DRY, use:

  • Functions and methods for repetitive operations.
  • Modules and libraries for common components.
  • Inheritance and composition in OOP.

Example in Node.js:

// Instead of repeating logic in different places
function calculateSum(a, b) {
  return a + b;
}

// Use the function wherever a sum is needed
const result = calculateSum(5, 10);