Writing one if per check works for two or three cases. By the fifth, the checks are mostly repetition, and the interesting part, the inputs and the expected results, is hard to see among the copies of the comparison. A table separates the two: the data in one place, the procedure in another. Put check cases in a slice of structs. Each row holds an input and its expected result. One loop applies the same comparison to every row, and the failure message names the input that failed.
Predict and run
Which boundary belongs in the accepted set?
package main
import (
"fmt"
)
func valid(n int) bool {
return n >= 1 && n <= 240
}
func main() {
cases := []struct {
minutes int
want bool
}{{0, false}, {1, true}, {240, true}, {241, false}}
for _, c := range cases {
if valid(c.minutes) != c.want {
panic(fmt.Sprintf("wrong result for %d", c.minutes))
}
}
fmt.Printf("%d checks passed\n", len(cases))
}Check your prediction
4 checks passedChange the upper bound in valid from <= to <. Which row catches it?
Reading the table
The struct type has no name. struct followed by its fields between braces is an anonymous struct type, used once, right here. That is fine for a table that only this loop uses; there is no need to declare a named type for it. The rows follow in a second pair of braces, and each row lists its values in the same order as the fields.
Lay the rows out so they are easy to scan. One row per line, with named fields, is clearer than a single long line once there are more than a few cases or more than two fields. Adding a case then means adding one line and nothing else.
Name each row
When a row fails, its message should make it easy to find. A name field describes what the row is for, such as upper bound or just above, which says far more than the raw input. It also documents why each case is in the table, so a reader can tell whether an important case is missing.
package main
import (
"errors"
"fmt"
)
func validate(minutes int) (int, error) {
if minutes < 1 || minutes > 240 {
return 0, errors.New("use 1-240 minutes")
}
return minutes, nil
}
func main() {
cases := []struct {
name string
minutes int
wantErr bool
}{
{name: "zero", minutes: 0, wantErr: true},
{name: "lower bound", minutes: 1, wantErr: false},
{name: "upper bound", minutes: 240, wantErr: false},
{name: "just above", minutes: 241, wantErr: true},
}
for _, c := range cases {
_, err := validate(c.minutes)
if (err != nil) != c.wantErr {
panic(fmt.Sprintf("%s: validate(%d) error = %v", c.name, c.minutes, err))
}
}
fmt.Printf("%d checks passed\n", len(cases))
}4 checks passedThe comparison (err != nil) != c.wantErr reads: "did we get an error, and was that what we wanted?". It works for both kinds of row, so the same loop checks accepted and rejected values.
Choose rows that can fail
A table is only as good as its rows. For a range such as 1 to 240, the four rows above are the minimum that can catch a wrong comparison at either end: each boundary, and the value just past it. A row in the middle, such as 120, is still worth keeping as the ordinary case. Before trusting a table, try what you did in the prediction above: break the function on purpose, and make sure at least one row fails.
One loop, many cases
Because the comparison lives in one loop, improving it improves every case at once. Add the actual value to the panic message, and every row benefits. That is much harder when each check is its own copied if.
Practice
Your turn
The starter defines valid. Check -1, 120 and 300 in one table and print how many cases passed.
package main
func valid(n int) bool {
return n >= 1 && n <= 240
}
func main() {
// Write your code here.
}Hint 1: the idea
Work out each expected value from the rule, not by running valid.
Hint 2: a first step
Create one row for each input and expected boolean.
Worked solution
package main
import (
"fmt"
)
func valid(n int) bool {
return n >= 1 && n <= 240
}
func main() {
cases := []struct {
minutes int
want bool
}{{-1, false}, {120, true}, {300, false}}
for _, c := range cases {
if valid(c.minutes) != c.want {
panic(fmt.Sprintf("wrong result for %d", c.minutes))
}
}
fmt.Printf("%d checks passed\n", len(cases))
}3 checks passedNone of these rows sits on a boundary, so changing <= to < would pass unnoticed. The example's 0, 1, 240 and 241 rows are the ones that guard the edges.
Completion is saved in this browser only. It does not measure mastery.