Spotting them, and when not to use them
After this: Name the pattern in a library call, and choose a function, a dictionary or an if when a pattern would be too much.
On this page · 7 sections · 4 checks
You now know three patterns by their shape. You have been using all three for a while without their names, because the libraries of Python and Java are full of them. This lesson points them out, shows a shorter way to write a strategy, and ends with the most useful skill of all: knowing when not to use a pattern.
Strategy: the sort key
Sorting has one job, putting items in order, and there are many ways to decide which item comes first. So the sort lets you hand in that way:
words = ["kiwi", "fig", "banana"]print(", ".join(sorted(words, key=len)))print(", ".join(sorted(words)))fig, kiwi, banana banana, fig, kiwi
import java.util.ArrayList;import java.util.Comparator;import java.util.List;
public class Main { public static void main(String[] args) { List<String> words = new ArrayList<>(List.of("kiwi", "fig", "banana")); words.sort(Comparator.comparingInt(String::length)); System.out.println(String.join(", ", words)); words.sort(Comparator.naturalOrder()); System.out.println(String.join(", ", words)); }}fig, kiwi, banana banana, fig, kiwi
- The first sort compares words by their length:
fig(3 letters),kiwi(4),banana(6). - The second compares them the usual way, alphabetically:
banana,fig,kiwi.
The sort's own code is the same both times. The way of ordering is a strategy. In Python it is the key function, which gives each item the value to sort by (here its length). In Java it is a Comparator object, which says which of two items comes first. The sort plays the part of the navigator, and the key or the Comparator plays the part of the route.
Factory: calls that choose the class
Some calls make an object for you and choose its class themselves:
- In Java,
List.of(1, 2)andList.of(1, 2, 3)return lists of two different hidden classes (in Java 21; the classes are not promised and may change). You use both as aListand never name the class.Integer.valueOf("42")is another factory: it may even hand back an object it made earlier instead of a new one. - In Python,
open("notes.txt")returns a text file object, andopen("notes.txt", "rb")returns an object of a different class that reads raw bytes. You ask for a file, andopendecides which class fits.
Each one is the same shape as NotifierFactory.create: what you ask for goes in, the right object comes out.
Observer: click listeners
Window and web libraries let you add listeners to a button. In Java's Swing library, button.addActionListener(listener) adds one to the button's list; in a web page, button.addEventListener("click", f) does the same. On each click the button goes through its list and calls each listener. The button is the channel, a click is an upload, and the listeners are the subscribers.
A strategy can be a function
A strategy with one method does not always need a class. In Python a function can be passed around like any other value, and in Java a short function can be written where it is needed. That short function is a .
def drive(km): return km * 60 // 40
def bike(km): return km * 60 // 15
def plan(km, minutes): return f"{minutes(km)} min"
print(plan(12, drive))print(plan(12, bike))18 min 48 min
import java.util.function.IntUnaryOperator;
public class Main { static String plan(int km, IntUnaryOperator minutes) { return minutes.applyAsInt(km) + " min"; }
public static void main(String[] args) { IntUnaryOperator drive = km -> km * 60 / 40; IntUnaryOperator bike = km -> km * 60 / 15; System.out.println(plan(12, drive)); System.out.println(plan(12, bike)); }}18 min 48 min
Walk through it:
driveandbikeare the two ways. In Python they are functions; in Java they are lambdas stored in variables of the typeIntUnaryOperator(a function from anintto anint).plantakes the distance and the way, and calls the way with the distance.plan(12, bike)gives48 min, as in lesson 2.
The shape is still Strategy: one job, swappable ways, and code that calls whichever it was given. It has fewer lines because there is no interface and no class per way. Once a way needs two methods or its own fields, go back to classes.
Add a walk way at 5 km an hour and plan 12 km with it. It should print 144 min.
When not to use a pattern
A pattern adds classes and arrows. They pay off when new kinds keep arriving, and they cost reading time when they do not. Some rules of thumb:
| Situation | Enough |
|---|---|
| two fixed cases, chosen in one place | an if |
| names to classes, with no other work in between | a dictionary from name to class (Python) or a map (Java) |
| one way of doing a job that needs no fields | a function or a lambda |
| one listener that will never be more | a direct call |
Use a pattern when a third kind is real, not when it is imagined.
Check yourself
You sort a list of words by length with sorted(words, key=len)words.sort(Comparator.comparingInt(String::length)). The sort's own code stays the same; you hand in the way to compare. Which pattern is that?
You call open("notes.txt", "rb")List.of(1, 2, 3). You never name a class: the call decides which class of object to make and hands it back. Which pattern is that?
A button in a window library has a method to add a listener. You add three listeners. When the user clicks, the button calls each of them. Which pattern is that?
A small script prints a report as plain text or as a table. There are only these two formats, nobody has asked for a third, and the choice is made in one place. A friend wants to add a FormatterFactory and a Formatter interface with two classes. What is the better advice?
Interview lens
- Say that the key you pass to a sort (Python's key, Java's Comparator) is a strategy.
- Say that List.of and Integer.valueOf in Java, and open in Python, are factories: the call decides how to make the object.
- Say that click listeners in window libraries are Observer: the button keeps a list and calls each one.
- Write a one-method strategy as a plain function in Python or a lambda in Java.
- Say when not to use a pattern: an if over two fixed cases, a dictionary (a map in Java) from name to class with no other work in between, or an object made in one place does not need one.