Lessons · Python · edge cases first
Test the ends first: nothing, one, everything the same
Most bugs live at the edges of the input: the empty case, the single item, all items equal, and the zero that divides. Test those first; the middle usually follows.
Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.
What it is for
sum(xs) / len(xs) works for every list you tried and crashes the first time a real user has no data. The empty list is not rare in production; it is the first thing production sends.
How to think about it
For any input, ask: what is the smallest possible one? The one-item one? The one where nothing differs? The one that makes a divisor zero? Decide the answer on purpose, write the test, then write the code.
Worked example
def monogram(names):Turn ['ada', 'grace'] into 'AG'.
if not names:The empty case, decided on purpose rather than discovered.
return ''No names, no initials. That is a decision, and it is written down.
return ''.join(n[0].upper() for n in names if n)
assert monogram([]) == ''Nothing. The case production sends first.
assert monogram(['ada']) == 'A'One. Off-by-one errors hide here and nowhere else.
assert monogram(['ada', '']) == 'A'An empty ITEM, which is a different edge from an empty list.
print(monogram(['ada', 'grace']))AG
Your turn
Decide the empty case for percent.
def percent(part, whole):
if whole == 0:
return
return round(100 * part / whole, 1)Solve one with the tests running
The trap
Testing only the happy path. It passes, ships, and the empty list arrives on the first day.