DRY — Don't Repeat Yourself
Introduction
Imagine you move to a new flat. You change your address on your bank's website, then with your insurer, then with your employer, then at the gym. Four places hold the same fact. The next time you move, you have to remember all four, and if you miss one, your post goes to the old address.
Code has the same trouble when one rule or one fact lives in several places. Change one copy, forget another, and the program no longer agrees with itself.
The DRY principle, short for Don't Repeat Yourself, comes from Andy Hunt and Dave Thomas's book The Pragmatic Programmer, first published in 1999. Its 20th anniversary edition states it as a tip: "Every piece of knowledge must have a single, unambiguous, authoritative representation within a system." In plain words, every rule and every fact should have one home, and everything else should use that home.
The picture shows the difference on one rule, a check for email addresses:

What DRY Means
The word that matters in the tip is knowledge. Dave Thomas put it bluntly in a 2003 interview: "Most people take DRY to mean you shouldn't duplicate code. That's not its intention." He went on: "A system's knowledge is far broader than just its code. It refers to database schemas, test plans, the build system, even documentation."
So the question DRY asks is whether one piece of knowledge, a rule, a fact or a decision, is written down in more than one place. Two lines of code that happen to look alike may be that, or may not. The reason to care is what happens over time. In the same interview he explains it: "if you have more than one way to express the same thing, at some point the two or three different representations will most likely fall out of step with each other." Andy Hunt summed up the goal: "One piece of knowledge in the domain changes, one piece of the system changes."
This is close to S — Single Responsibility Principle, and the two work together. The single responsibility principle asks that each class has one reason to change. DRY asks that each piece of knowledge lives in one place, so that one change in the business means one change in the code.
Three Copies of One Rule
Here is the problem in code. Three forms check email addresses, and each one has its own copy of the check. The business has just added a rule, at most 30 characters, and the developer updated the registration form's copy. The other two copies were missed. The program sends three addresses to all three forms.
import re
from typing import Callable
# Three forms check email addresses, each with its own copy of the same check. The
# business has just added a rule, at most 30 characters, and only the registration
# form's copy was updated: the other two copies were missed.
class UserRegistration:
_EMAIL = re.compile(r"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}")
def sign_up(self, email: str) -> None:
if not self._EMAIL.fullmatch(email):
raise ValueError("not an email address")
if len(email) > 30: # the new rule, added here only
raise ValueError("longer than 30 characters")
print(f"Registration: account made for {email}")
class NewsletterSubscription:
_EMAIL = re.compile(r"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}")
def subscribe(self, email: str) -> None:
if not self._EMAIL.fullmatch(email):
raise ValueError("not an email address")
print(f"Newsletter: {email} subscribed")
class ContactForm:
_EMAIL = re.compile(r"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}")
def submit(self, email: str, message: str) -> None:
if not self._EMAIL.fullmatch(email):
raise ValueError("not an email address")
print(f'Contact: "{message}" from {email}')
# Tries one form with one address and says what happened
def attempt(form: str, email: str, send: Callable[[], None]) -> None:
try:
send()
except ValueError as error:
print(f"{form} refused {email}: {error}")
def main() -> None:
registration = UserRegistration()
newsletter = NewsletterSubscription()
contact = ContactForm()
for email in ["ann@shop.com", "jo@shop", "a.very.long.name.indeed@mail.com"]:
attempt("Registration", email, lambda: registration.sign_up(email))
attempt("Newsletter", email, lambda: newsletter.subscribe(email))
attempt("Contact", email, lambda: contact.submit(email, "Hello"))
if __name__ == "__main__":
main()import java.util.regex.Pattern;
// Three forms check email addresses, each with its own copy of the same check. The
// business has just added a rule, at most 30 characters, and only the registration
// form's copy was updated: the other two copies were missed.
class UserRegistration {
private static final Pattern EMAIL =
Pattern.compile("^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}$");
void signUp(String email) {
if (!EMAIL.matcher(email).matches()) {
throw new IllegalArgumentException("not an email address");
}
if (email.length() > 30) { // the new rule, added here only
throw new IllegalArgumentException("longer than 30 characters");
}
System.out.println("Registration: account made for " + email);
}
}
class NewsletterSubscription {
private static final Pattern EMAIL =
Pattern.compile("^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}$");
void subscribe(String email) {
if (!EMAIL.matcher(email).matches()) {
throw new IllegalArgumentException("not an email address");
}
System.out.println("Newsletter: " + email + " subscribed");
}
}
class ContactForm {
private static final Pattern EMAIL =
Pattern.compile("^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}$");
void submit(String email, String message) {
if (!EMAIL.matcher(email).matches()) {
throw new IllegalArgumentException("not an email address");
}
System.out.println("Contact: \"" + message + "\" from " + email);
}
}
public class Signups {
// Tries one form with one address and says what happened
static void attempt(String form, String email, Runnable send) {
try {
send.run();
} catch (IllegalArgumentException e) {
System.out.println(form + " refused " + email + ": " + e.getMessage());
}
}
public static void main(String[] args) {
UserRegistration registration = new UserRegistration();
NewsletterSubscription newsletter = new NewsletterSubscription();
ContactForm contact = new ContactForm();
String[] addresses =
{"ann@shop.com", "jo@shop", "a.very.long.name.indeed@mail.com"};
for (String email : addresses) {
attempt("Registration", email, () -> registration.signUp(email));
attempt("Newsletter", email, () -> newsletter.subscribe(email));
attempt("Contact", email, () -> contact.submit(email, "Hello"));
}
}
}#include <functional>
#include <iostream>
#include <regex>
#include <stdexcept>
#include <string>
// Three forms check email addresses, each with its own copy of the same check. The
// business has just added a rule, at most 30 characters, and only the registration
// form's copy was updated: the other two copies were missed.
class UserRegistration {
public:
void signUp(const std::string& email) {
static const std::regex pattern(
R"([A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,})");
if (!std::regex_match(email, pattern)) {
throw std::invalid_argument("not an email address");
}
if (email.size() > 30) { // the new rule, added here only
throw std::invalid_argument("longer than 30 characters");
}
std::cout << "Registration: account made for " << email << "\n";
}
};
class NewsletterSubscription {
public:
void subscribe(const std::string& email) {
static const std::regex pattern(
R"([A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,})");
if (!std::regex_match(email, pattern)) {
throw std::invalid_argument("not an email address");
}
std::cout << "Newsletter: " << email << " subscribed\n";
}
};
class ContactForm {
public:
void submit(const std::string& email, const std::string& message) {
static const std::regex pattern(
R"([A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,})");
if (!std::regex_match(email, pattern)) {
throw std::invalid_argument("not an email address");
}
std::cout << "Contact: \"" << message << "\" from " << email << "\n";
}
};
// Tries one form with one address and says what happened
void attempt(const std::string& form, const std::string& email,
const std::function<void()>& send) {
try {
send();
} catch (const std::invalid_argument& e) {
std::cout << form << " refused " << email << ": " << e.what() << "\n";
}
}
int main() {
UserRegistration registration;
NewsletterSubscription newsletter;
ContactForm contact;
for (const std::string email :
{"ann@shop.com", "jo@shop", "a.very.long.name.indeed@mail.com"}) {
attempt("Registration", email, [&] { registration.signUp(email); });
attempt("Newsletter", email, [&] { newsletter.subscribe(email); });
attempt("Contact", email, [&] { contact.submit(email, "Hello"); });
}
return 0;
}// Three forms check email addresses, each with its own copy of the same check. The
// business has just added a rule, at most 30 characters, and only the registration
// form's copy was updated: the other two copies were missed.
class UserRegistration {
private static readonly EMAIL = /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$/;
signUp(email: string): void {
if (!UserRegistration.EMAIL.test(email)) {
throw new Error("not an email address");
}
if (email.length > 30) { // the new rule, added here only
throw new Error("longer than 30 characters");
}
console.log(`Registration: account made for ${email}`);
}
}
class NewsletterSubscription {
private static readonly EMAIL = /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$/;
subscribe(email: string): void {
if (!NewsletterSubscription.EMAIL.test(email)) {
throw new Error("not an email address");
}
console.log(`Newsletter: ${email} subscribed`);
}
}
class ContactForm {
private static readonly EMAIL = /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$/;
submit(email: string, message: string): void {
if (!ContactForm.EMAIL.test(email)) {
throw new Error("not an email address");
}
console.log(`Contact: "${message}" from ${email}`);
}
}
type Send = () => void;
// Tries one form with one address and says what happened
function attempt(form: string, email: string, send: Send): void {
try {
send();
} catch (error) {
console.log(`${form} refused ${email}: ${(error as Error).message}`);
}
}
function main(): void {
const registration = new UserRegistration();
const newsletter = new NewsletterSubscription();
const contact = new ContactForm();
for (const email of ["ann@shop.com", "jo@shop", "a.very.long.name.indeed@mail.com"]) {
attempt("Registration", email, () => registration.signUp(email));
attempt("Newsletter", email, () => newsletter.subscribe(email));
attempt("Contact", email, () => contact.submit(email, "Hello"));
}
}
main();using System;
using System.Text.RegularExpressions;
// Three forms check email addresses, each with its own copy of the same check. The
// business has just added a rule, at most 30 characters, and only the registration
// form's copy was updated: the other two copies were missed.
public class UserRegistration
{
private static readonly Regex Email =
new Regex(@"^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$");
public void SignUp(string email)
{
if (!Email.IsMatch(email))
{
throw new ArgumentException("not an email address");
}
if (email.Length > 30) // the new rule, added here only
{
throw new ArgumentException("longer than 30 characters");
}
Console.WriteLine("Registration: account made for " + email);
}
}
public class NewsletterSubscription
{
private static readonly Regex Email =
new Regex(@"^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$");
public void Subscribe(string email)
{
if (!Email.IsMatch(email))
{
throw new ArgumentException("not an email address");
}
Console.WriteLine("Newsletter: " + email + " subscribed");
}
}
public class ContactForm
{
private static readonly Regex Email =
new Regex(@"^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$");
public void Submit(string email, string message)
{
if (!Email.IsMatch(email))
{
throw new ArgumentException("not an email address");
}
Console.WriteLine("Contact: \"" + message + "\" from " + email);
}
}
public class Signups
{
// Tries one form with one address and says what happened
static void Attempt(string form, string email, Action send)
{
try
{
send();
}
catch (ArgumentException e)
{
Console.WriteLine(form + " refused " + email + ": " + e.Message);
}
}
public static void Main(string[] args)
{
UserRegistration registration = new UserRegistration();
NewsletterSubscription newsletter = new NewsletterSubscription();
ContactForm contact = new ContactForm();
string[] addresses =
{ "ann@shop.com", "jo@shop", "a.very.long.name.indeed@mail.com" };
foreach (string email in addresses)
{
Attempt("Registration", email, () => registration.SignUp(email));
Attempt("Newsletter", email, () => newsletter.Subscribe(email));
Attempt("Contact", email, () => contact.Submit(email, "Hello"));
}
}
}package main
import (
"errors"
"fmt"
"regexp"
)
// Three forms check email addresses, each with its own copy of the same check. The
// business has just added a rule, at most 30 characters, and only the registration
// form's copy was updated: the other two copies were missed.
// UserRegistration makes accounts.
type UserRegistration struct{}
// the registration form's own copy of the check
var registrationEmail = regexp.MustCompile(
`^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$`)
// SignUp checks the address and makes the account.
func (UserRegistration) SignUp(email string) error {
if !registrationEmail.MatchString(email) {
return errors.New("not an email address")
}
if len(email) > 30 { // the new rule, added here only
return errors.New("longer than 30 characters")
}
fmt.Printf("Registration: account made for %s\n", email)
return nil
}
// NewsletterSubscription signs addresses up for the newsletter.
type NewsletterSubscription struct{}
// the newsletter form's own copy of the check
var newsletterEmail = regexp.MustCompile(
`^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$`)
// Subscribe checks the address and signs it up.
func (NewsletterSubscription) Subscribe(email string) error {
if !newsletterEmail.MatchString(email) {
return errors.New("not an email address")
}
fmt.Printf("Newsletter: %s subscribed\n", email)
return nil
}
// ContactForm takes messages.
type ContactForm struct{}
// the contact form's own copy of the check
var contactEmail = regexp.MustCompile(
`^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$`)
// Submit checks the address and takes the message.
func (ContactForm) Submit(email, message string) error {
if !contactEmail.MatchString(email) {
return errors.New("not an email address")
}
fmt.Printf("Contact: \"%s\" from %s\n", message, email)
return nil
}
// attempt tries one form with one address and says what happened.
func attempt(form, email string, send func() error) {
if err := send(); err != nil {
fmt.Printf("%s refused %s: %v\n", form, email, err)
}
}
func main() {
registration := UserRegistration{}
newsletter := NewsletterSubscription{}
contact := ContactForm{}
addresses := []string{"ann@shop.com", "jo@shop", "a.very.long.name.indeed@mail.com"}
for _, email := range addresses {
attempt("Registration", email,
func() error { return registration.SignUp(email) })
attempt("Newsletter", email,
func() error { return newsletter.Subscribe(email) })
attempt("Contact", email,
func() error { return contact.Submit(email, "Hello") })
}
}It prints:
Registration: account made for ann@shop.com
Newsletter: ann@shop.com subscribed
Contact: "Hello" from ann@shop.com
Registration refused jo@shop: not an email address
Newsletter refused jo@shop: not an email address
Contact refused jo@shop: not an email address
Registration refused a.very.long.name.indeed@mail.com: longer than 30 characters
Newsletter: a.very.long.name.indeed@mail.com subscribed
Contact: "Hello" from a.very.long.name.indeed@mail.com
The first six lines look fine: a good address is accepted everywhere, and jo@shop is refused everywhere, because the three copies of the old check still agree. The last three lines show the cost. The long address, 32 characters, is refused by the registration form and accepted by the newsletter and the contact form. Nothing crashed, and each copy does exactly what its code says, which is why such a bug is easy to miss: the copies have fallen out of step.
One Rule in One Place
The fix gives the rule one home. EmailValidator holds the check and the new limit, and every form asks it.
import re
from typing import Callable
# The rule lives in one place. Every form asks EmailValidator, so the new rule, at
# most 30 characters, reaches all three forms at once.
class EmailValidator:
_EMAIL = re.compile(r"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}")
_MAX_LENGTH = 30
@staticmethod
def validate(email: str) -> None:
if not EmailValidator._EMAIL.fullmatch(email):
raise ValueError("not an email address")
if len(email) > EmailValidator._MAX_LENGTH:
raise ValueError(f"longer than {EmailValidator._MAX_LENGTH} characters")
class UserRegistration:
def sign_up(self, email: str) -> None:
EmailValidator.validate(email)
print(f"Registration: account made for {email}")
class NewsletterSubscription:
def subscribe(self, email: str) -> None:
EmailValidator.validate(email)
print(f"Newsletter: {email} subscribed")
class ContactForm:
def submit(self, email: str, message: str) -> None:
EmailValidator.validate(email)
print(f'Contact: "{message}" from {email}')
# Tries one form with one address and says what happened
def attempt(form: str, email: str, send: Callable[[], None]) -> None:
try:
send()
except ValueError as error:
print(f"{form} refused {email}: {error}")
def main() -> None:
registration = UserRegistration()
newsletter = NewsletterSubscription()
contact = ContactForm()
for email in ["ann@shop.com", "jo@shop", "a.very.long.name.indeed@mail.com"]:
attempt("Registration", email, lambda: registration.sign_up(email))
attempt("Newsletter", email, lambda: newsletter.subscribe(email))
attempt("Contact", email, lambda: contact.submit(email, "Hello"))
if __name__ == "__main__":
main()import java.util.regex.Pattern;
// The rule lives in one place. Every form asks EmailValidator, so the new rule, at
// most 30 characters, reaches all three forms at once.
final class EmailValidator {
private static final Pattern EMAIL =
Pattern.compile("^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}$");
private static final int MAX_LENGTH = 30;
static void validate(String email) {
if (!EMAIL.matcher(email).matches()) {
throw new IllegalArgumentException("not an email address");
}
if (email.length() > MAX_LENGTH) {
throw new IllegalArgumentException(
"longer than " + MAX_LENGTH + " characters");
}
}
}
class UserRegistration {
void signUp(String email) {
EmailValidator.validate(email);
System.out.println("Registration: account made for " + email);
}
}
class NewsletterSubscription {
void subscribe(String email) {
EmailValidator.validate(email);
System.out.println("Newsletter: " + email + " subscribed");
}
}
class ContactForm {
void submit(String email, String message) {
EmailValidator.validate(email);
System.out.println("Contact: \"" + message + "\" from " + email);
}
}
public class Signups {
// Tries one form with one address and says what happened
static void attempt(String form, String email, Runnable send) {
try {
send.run();
} catch (IllegalArgumentException e) {
System.out.println(form + " refused " + email + ": " + e.getMessage());
}
}
public static void main(String[] args) {
UserRegistration registration = new UserRegistration();
NewsletterSubscription newsletter = new NewsletterSubscription();
ContactForm contact = new ContactForm();
String[] addresses =
{"ann@shop.com", "jo@shop", "a.very.long.name.indeed@mail.com"};
for (String email : addresses) {
attempt("Registration", email, () -> registration.signUp(email));
attempt("Newsletter", email, () -> newsletter.subscribe(email));
attempt("Contact", email, () -> contact.submit(email, "Hello"));
}
}
}#include <functional>
#include <iostream>
#include <regex>
#include <stdexcept>
#include <string>
// The rule lives in one place. Every form asks EmailValidator, so the new rule, at
// most 30 characters, reaches all three forms at once.
class EmailValidator {
public:
static void validate(const std::string& email) {
static const std::regex pattern(
R"([A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,})");
if (!std::regex_match(email, pattern)) {
throw std::invalid_argument("not an email address");
}
if (email.size() > MAX_LENGTH) {
throw std::invalid_argument("longer than " + std::to_string(MAX_LENGTH) +
" characters");
}
}
private:
static constexpr std::size_t MAX_LENGTH = 30;
};
class UserRegistration {
public:
void signUp(const std::string& email) {
EmailValidator::validate(email);
std::cout << "Registration: account made for " << email << "\n";
}
};
class NewsletterSubscription {
public:
void subscribe(const std::string& email) {
EmailValidator::validate(email);
std::cout << "Newsletter: " << email << " subscribed\n";
}
};
class ContactForm {
public:
void submit(const std::string& email, const std::string& message) {
EmailValidator::validate(email);
std::cout << "Contact: \"" << message << "\" from " << email << "\n";
}
};
// Tries one form with one address and says what happened
void attempt(const std::string& form, const std::string& email,
const std::function<void()>& send) {
try {
send();
} catch (const std::invalid_argument& e) {
std::cout << form << " refused " << email << ": " << e.what() << "\n";
}
}
int main() {
UserRegistration registration;
NewsletterSubscription newsletter;
ContactForm contact;
for (const std::string email :
{"ann@shop.com", "jo@shop", "a.very.long.name.indeed@mail.com"}) {
attempt("Registration", email, [&] { registration.signUp(email); });
attempt("Newsletter", email, [&] { newsletter.subscribe(email); });
attempt("Contact", email, [&] { contact.submit(email, "Hello"); });
}
return 0;
}// The rule lives in one place. Every form asks EmailValidator, so the new rule, at
// most 30 characters, reaches all three forms at once.
class EmailValidator {
private static readonly EMAIL = /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$/;
private static readonly MAX_LENGTH = 30;
static validate(email: string): void {
if (!EmailValidator.EMAIL.test(email)) {
throw new Error("not an email address");
}
if (email.length > EmailValidator.MAX_LENGTH) {
throw new Error(`longer than ${EmailValidator.MAX_LENGTH} characters`);
}
}
}
class UserRegistration {
signUp(email: string): void {
EmailValidator.validate(email);
console.log(`Registration: account made for ${email}`);
}
}
class NewsletterSubscription {
subscribe(email: string): void {
EmailValidator.validate(email);
console.log(`Newsletter: ${email} subscribed`);
}
}
class ContactForm {
submit(email: string, message: string): void {
EmailValidator.validate(email);
console.log(`Contact: "${message}" from ${email}`);
}
}
type Send = () => void;
// Tries one form with one address and says what happened
function attempt(form: string, email: string, send: Send): void {
try {
send();
} catch (error) {
console.log(`${form} refused ${email}: ${(error as Error).message}`);
}
}
function main(): void {
const registration = new UserRegistration();
const newsletter = new NewsletterSubscription();
const contact = new ContactForm();
for (const email of ["ann@shop.com", "jo@shop", "a.very.long.name.indeed@mail.com"]) {
attempt("Registration", email, () => registration.signUp(email));
attempt("Newsletter", email, () => newsletter.subscribe(email));
attempt("Contact", email, () => contact.submit(email, "Hello"));
}
}
main();using System;
using System.Text.RegularExpressions;
// The rule lives in one place. Every form asks EmailValidator, so the new rule, at
// most 30 characters, reaches all three forms at once.
public static class EmailValidator
{
private static readonly Regex Email =
new Regex(@"^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$");
private const int MaxLength = 30;
public static void Validate(string email)
{
if (!Email.IsMatch(email))
{
throw new ArgumentException("not an email address");
}
if (email.Length > MaxLength)
{
throw new ArgumentException("longer than " + MaxLength + " characters");
}
}
}
public class UserRegistration
{
public void SignUp(string email)
{
EmailValidator.Validate(email);
Console.WriteLine("Registration: account made for " + email);
}
}
public class NewsletterSubscription
{
public void Subscribe(string email)
{
EmailValidator.Validate(email);
Console.WriteLine("Newsletter: " + email + " subscribed");
}
}
public class ContactForm
{
public void Submit(string email, string message)
{
EmailValidator.Validate(email);
Console.WriteLine("Contact: \"" + message + "\" from " + email);
}
}
public class Signups
{
// Tries one form with one address and says what happened
static void Attempt(string form, string email, Action send)
{
try
{
send();
}
catch (ArgumentException e)
{
Console.WriteLine(form + " refused " + email + ": " + e.Message);
}
}
public static void Main(string[] args)
{
UserRegistration registration = new UserRegistration();
NewsletterSubscription newsletter = new NewsletterSubscription();
ContactForm contact = new ContactForm();
string[] addresses =
{ "ann@shop.com", "jo@shop", "a.very.long.name.indeed@mail.com" };
foreach (string email in addresses)
{
Attempt("Registration", email, () => registration.SignUp(email));
Attempt("Newsletter", email, () => newsletter.Subscribe(email));
Attempt("Contact", email, () => contact.Submit(email, "Hello"));
}
}
}package main
import (
"errors"
"fmt"
"regexp"
)
// The rule lives in one place. Every form asks EmailValidator, so the new rule, at
// most 30 characters, reaches all three forms at once.
// EmailValidator holds the rule's one copy; Go has no static methods, so the forms
// call it on the type's zero value.
type EmailValidator struct{}
var emailPattern = regexp.MustCompile(
`^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$`)
const maxLength = 30
// Validate checks an address against the rule.
func (EmailValidator) Validate(email string) error {
if !emailPattern.MatchString(email) {
return errors.New("not an email address")
}
if len(email) > maxLength {
return fmt.Errorf("longer than %d characters", maxLength)
}
return nil
}
// UserRegistration makes accounts.
type UserRegistration struct{}
// SignUp checks the address and makes the account.
func (UserRegistration) SignUp(email string) error {
if err := (EmailValidator{}).Validate(email); err != nil {
return err
}
fmt.Printf("Registration: account made for %s\n", email)
return nil
}
// NewsletterSubscription signs addresses up for the newsletter.
type NewsletterSubscription struct{}
// Subscribe checks the address and signs it up.
func (NewsletterSubscription) Subscribe(email string) error {
if err := (EmailValidator{}).Validate(email); err != nil {
return err
}
fmt.Printf("Newsletter: %s subscribed\n", email)
return nil
}
// ContactForm takes messages.
type ContactForm struct{}
// Submit checks the address and takes the message.
func (ContactForm) Submit(email, message string) error {
if err := (EmailValidator{}).Validate(email); err != nil {
return err
}
fmt.Printf("Contact: \"%s\" from %s\n", message, email)
return nil
}
// attempt tries one form with one address and says what happened.
func attempt(form, email string, send func() error) {
if err := send(); err != nil {
fmt.Printf("%s refused %s: %v\n", form, email, err)
}
}
func main() {
registration := UserRegistration{}
newsletter := NewsletterSubscription{}
contact := ContactForm{}
addresses := []string{"ann@shop.com", "jo@shop", "a.very.long.name.indeed@mail.com"}
for _, email := range addresses {
attempt("Registration", email,
func() error { return registration.SignUp(email) })
attempt("Newsletter", email,
func() error { return newsletter.Subscribe(email) })
attempt("Contact", email,
func() error { return contact.Submit(email, "Hello") })
}
}It prints:
Registration: account made for ann@shop.com
Newsletter: ann@shop.com subscribed
Contact: "Hello" from ann@shop.com
Registration refused jo@shop: not an email address
Newsletter refused jo@shop: not an email address
Contact refused jo@shop: not an email address
Registration refused a.very.long.name.indeed@mail.com: longer than 30 characters
Newsletter refused a.very.long.name.indeed@mail.com: longer than 30 characters
Contact refused a.very.long.name.indeed@mail.com: longer than 30 characters
Now all three forms refuse the long address for the same reason. The next time the rule changes, say to allow 40 characters, there is one line to edit, and every form follows it.
EmailValidator is not a thing from the business, like a customer or an order. It exists only to give the rule a home, which GRASP Principles — General Responsibility Assignment calls a pure fabrication.
Take the same change one step at a time and watch what each form does with the same address:

Beyond Code: Data and Knowledge
Repeated code is the easiest kind to see. Two other kinds are harder to spot.
Data. A shop keeps a customer's address in its customers table and copies it into every order. When the customer moves, the customers table is updated and the copies in the orders still hold the old address. Which one is right? Keep the address in one place, and let each order refer to its customer. If an order really must keep the address it was sent to, which is a fair business need, store that copy on purpose and name it for what it is, such as address_at_order_time, so nobody mistakes it for the current address.
Knowledge. A pricing module works out tax with 0.08, and a reporting module prints the rate as 8. They do not look alike, yet they are the same fact: the sales tax rate. When the rate becomes 8.5 percent, someone updates pricing to 0.085, and the reports keep saying 8. Keep the rate in one place, a constant or a setting, and let both modules read it. This kind is hard to find, because the copies look nothing like each other.
Common Mistakes
Merging code that only looks the same. A function that works out an employee's bonus and one that works out a customer's discount may both multiply an amount by a percentage today. They are still two rules, owned by different people, and they will change for different reasons. Merged into one function, a change to discounts would change bonuses too. DRY is about knowledge, so ask whether the two pieces of code say the same thing, and leave them apart when they only look alike.
Extracting too early. Seeing two similar lines and building a shared helper with three settings often leaves something harder to read than the copies were. Dave Thomas describes a calmer habit for the larger case of a code generator: "chances are good I will generate the products manually first", and only when he comes back to the same job does he decide to automate it. The same patience works for helpers. YAGNI — You Aren't Gonna Need It goes further into building only what is needed now.
Sharing across service boundaries. Two separate services that share a library of checks are tied together: a change to the library has to be released to both, and neither can move alone. Inside one program, one home for each rule is the right aim. Between services that are deployed on their own, a little copying can cost less than that tie.
When It Applies
DRY helps most where one business rule or one fact is written in several places: a limit, a tax rate, a format, a setting that appears in more than one file. A sign is a change that sends you to edit many files for one reason, which Code Smells — Recognizing Bad Design calls shotgun surgery.
It is the wrong tool when the copies only look alike, when sharing would tie together parts that should change on their own, or when the shared version would be harder to follow than the copies it replaces. The aim is a program that is cheap to change correctly, so judge each case by that.
KISS — Keep It Simple, Stupid comes next, about keeping the design no more complicated than the problem.
Key Takeaways
- DRY means every piece of knowledge, a rule or a fact, has one home; it is about knowledge, and code that only looks alike is not a repeat.
- Copies of one rule fall out of step: a change that reaches one copy leaves the program answering the same question two ways.
- Knowledge can repeat in data and in different forms, an address kept twice or a rate written as 0.08 and as 8, as well as in code.
- Give the rule one home only when the copies say the same thing, and keep separate services free to change on their own.