DRY
easy 40 minDon't repeat yourself: every piece of knowledge has one home, and everything else asks that home.
Watch lesson4:18
One home for each rule
Read it, run it, change a line and run it again.
Loading editor…
Email and tax have one home. Three totals and three account actions use them.
The same in Java
import java.time.LocalDate;import java.util.Map;import java.util.TreeMap;record EmailAddress(String value) { static EmailAddress parse(String raw) { String text = raw == null ? "" : raw.strip(); int at = text.lastIndexOf('@'); String domain = text.substring(at + 1); boolean ok = at > 0 && !text.contains(" ") && domain.contains(".") && !domain.startsWith(".") && !domain.endsWith(".") && !domain.contains(".."); if (!ok) throw new IllegalArgumentException("email: expected name@domain"); return new EmailAddress(text.substring(0, at) + "@" + domain.toLowerCase()); }}final class Password { static void check(String text) { if (text == null || text.length() < 8) throw new IllegalArgumentException("password: at least 8 characters"); }}final class TaxTable { private final TreeMap<LocalDate, Integer> rates; TaxTable(Map<LocalDate, Integer> rates) { this.rates = new TreeMap<>(rates); } long withTax(long cents, LocalDate day) { var rate = rates.floorEntry(day); if (rate == null) throw new IllegalArgumentException("no tax rate for " + day); return cents + (cents * rate.getValue() + 5000) / 10000; }}class UserRegistration { void registerUser(String email, String password) { EmailAddress address = EmailAddress.parse(email); Password.check(password); System.out.println("registered " + address.value()); } void updateEmail(String email) { System.out.println("changed to " + EmailAddress.parse(email).value()); }}public class Main { public static void main(String[] args) { var tax = new TaxTable(Map.of(LocalDate.of(2024, 1, 1), 800, LocalDate.of(2026, 7, 1), 850)); new UserRegistration().registerUser("noor@Hall.example", "long enough"); System.out.println(tax.withTax(10000, LocalDate.of(2026, 6, 30))); // 10800 System.out.println(tax.withTax(10000, LocalDate.of(2026, 7, 1))); // 10850 }}The same in TypeScript
class EmailAddress { private constructor(readonly value: string) {} static parse(raw: string | null): EmailAddress { const text = (raw ?? "").trim(); const at = text.lastIndexOf("@"); const parts = text.slice(at + 1).split("."); if (at < 1 || text.includes(" ") || parts.length < 2 || parts.includes("")) { throw new Error("email: expected name@domain"); } return new EmailAddress(text.slice(0, at) + "@" + parts.join(".").toLowerCase()); }}class TaxTable { constructor(private readonly rates: readonly (readonly [string, number])[]) {} withTax(cents: number, day: string): number { const found = this.rates.filter(([start]) => start <= day).pop(); if (!found) throw new Error("no tax rate for " + day); return cents + Math.floor((cents * found[1] + 5000) / 10000); }}const TAX = new TaxTable([["2024-01-01", 800], ["2026-07-01", 850]]);const orderTotal = (prices: number[], day: string) => TAX.withTax(prices.reduce((a, b) => a + b, 0), day);const subscriptionTotal = (monthly: number, months: number, day: string) => TAX.withTax(monthly * months, day);const serviceFee = (hours: number, rate: number, day: string) => TAX.withTax(hours * rate, day);console.log(EmailAddress.parse("noor@Hall.example").value);console.log(orderTotal([10000], "2026-06-30"), subscriptionTotal(5000, 2, "2026-07-01"), serviceFee(4, 2500, "2026-07-01"));The same in C++
#include <iostream>#include <map>#include <stdexcept>#include <string>#include <vector>class EmailAddress { std::string value_; explicit EmailAddress(std::string v) : value_(std::move(v)) {}public: static EmailAddress parse(const std::string& text) { auto at = text.rfind('@'); bool ok = at != std::string::npos && at > 0 && text.find(' ') == std::string::npos; std::string domain = ok ? text.substr(at + 1) : ""; ok = ok && domain.find('.') != std::string::npos && domain.front() != '.' && domain.back() != '.' && domain.find("..") == std::string::npos; if (!ok) throw std::invalid_argument("email: expected name@domain"); return EmailAddress(text); } const std::string& value() const { return value_; }};class TaxTable { std::map<std::string, int> rates_; // ISO date, hundredths of a percentpublic: explicit TaxTable(std::map<std::string, int> rates) : rates_(std::move(rates)) {} long withTax(long cents, const std::string& day) const { auto it = rates_.upper_bound(day); if (it == rates_.begin()) throw std::invalid_argument("no tax rate for " + day); return cents + (cents * std::prev(it)->second + 5000) / 10000; }};template <typename T>void printList(const std::vector<T>& items) { std::cout << "["; for (std::size_t i = 0; i < items.size(); ++i) std::cout << (i ? ", " : "") << items[i]; std::cout << "]\n";}int main() { TaxTable tax({{"2024-01-01", 800}, {"2026-07-01", 850}}); std::cout << EmailAddress::parse("noor@hall.example").value() << "\n"; printList(std::vector<long>{tax.withTax(10000, "2026-06-30"), tax.withTax(10000, "2026-07-01")}); printList(std::vector<std::string>{"hello", "world"}); try { EmailAddress::parse("abc@"); } catch (const std::invalid_argument& e) { std::cout << e.what() << "\n"; }}