97 Things Every Programmer Should Know

(Chris Devlin) #1

Collective Wisdom from the Experts 61


Repetition in Logic Calls for Abstraction


Repetition in logic can take many forms. Copy-and-paste if-then or switch-
case logic is among the easiest to detect and correct. Many design patterns
have the explicit goal of reducing or eliminating duplication in logic within
an application. If an object typically requires several things to happen before
it can be used, this can be accomplished with an Abstract Factory or a Factory
Method pattern. If an object has many possible variations in its behavior, these
behaviors can be injected using the Strategy pattern rather than large if-then
structures. In fact, the formulation of design patterns themselves is an attempt
to reduce the duplication of effort required to solve common problems and
discuss such solutions. In addition, DRY can be applied to structures, such as
database schema, resulting in normalization.


A Matter of Principle


Other software principles are also related to DRY. The Once and Only Once prin-
ciple, which applies only to the functional behavior of code, can be thought of as
a subset of DRY. The Open/Closed Principle, which states that “software entities
should be open for extension, but closed for modification,” only works in practice
when DRY is followed. Likewise, the well-known Single Responsibility Principle,
which requires that a class have “only one reason to change,” relies on DRY.


When followed with regard to structure, logic, process, and function, the DRY
principle provides fundamental guidance to software developers and aids the
creation of simpler, more maintainable, higher-quality applications. While there
are scenarios where repetition can be necessary to meet performance or other
requirements (e.g., data denormalization in a database), it should be used only
where it directly addresses an actual rather than an imagined problem.

Free download pdf