Skip to content
Plurafy

DRY Principle

The DRY (Don’t Repeat Yourself) Principle is a software development concept aimed at reducing the repetition of code patterns, logic, or information. By adhering to this principle, developers can improve code maintainability, readability, and reduce the risk of bugs.

  • Single Source of Truth: Each piece of knowledge or logic should have a single, unambiguous representation within a system.
  • Code Reuse: Avoid duplicating code by creating reusable functions, classes, or modules.
  • Abstraction: Encapsulate common patterns or logic into abstractions to prevent repetition.
  • Maintainability: Changes need to be made in only one place, reducing the likelihood of errors.
  • Readability: Code is easier to understand when it is not cluttered with repeated logic.
  • Reduced Bugs: Minimizing duplication reduces the chances of inconsistencies and errors.

Instead of repeating the same logic in multiple places:

# Repeated logic
def calculate_area_rectangle(length, width):
return length * width
def calculate_area_square(side):
return side * side

You can abstract the common logic:

def calculate_area(shape, **dimensions):
if shape == "rectangle":
return dimensions["length"] * dimensions["width"]
elif shape == "square":
return dimensions["side"] * dimensions["side"]