DRY
easy 40 minDon't repeat yourself: every piece of knowledge has one home, and everything else asks that home.
Watch lesson4:18
Techniques
Choose the lightest way to share.
The point: start with the smallest tool. A constant, then a function, then a type, then a module.
Only the type differs
Generics instead of copies
C++
#include <iostream>#include <string>#include <vector>template <typename T>void printList(const std::vector<T>& items) { std::cout << "["; for (std::size_t i = 0; i < items.size(); ++i) { if (i > 0) std::cout << ", "; std::cout << items[i]; } std::cout << "]\n";}int main() { printList(std::vector<int>{1, 2, 3}); // [1, 2, 3] printList(std::vector<std::string>{"hello", "world"}); // [hello, world]}Only the middle differs
A function as a parameter
Python
def with_report(name, work): try: result = work() except Exception as e: return f"{name}: failed ({e})" return f"{name}: ok ({result})"print(with_report("import", lambda: 12 + 30))print(with_report("export", lambda: 1 // 0))The same idea with classes is the template method or a strategy.
Which tool first?
| What repeats | Lightest tool |
|---|---|
| A value | Constant |
| Steps | Function |
| Steps around a different middle | Function that takes a function |
| A check that belongs to a value | Value class |
| A loop over another type | Generic |
| Branches with other values | Table |
| A shape in two languages | Schema and generator |