AlgoViz

DRY

easy 40 min

Don'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]}
Two functions that print a list of numbers and a list of words had the same loop. A template keeps one loop. It works for each type that can be printed.

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))
Open, try, close, report: the frame is the same for each job. Only the middle is different, so the middle is handed in.
Edit and run it in your browser

The same idea with classes is the template method or a strategy.

Which tool first?

What repeatsLightest tool
A valueConstant
StepsFunction
Steps around a different middleFunction that takes a function
A check that belongs to a valueValue class
A loop over another typeGeneric
Branches with other valuesTable
A shape in two languagesSchema and generator