Skip to content

Trace Input Through the Files

The Course
•
15 min study

Reading a program you did not write is a skill of its own, and it is most of what professional programmers do every day. The best way to build it is to pick one input and follow it through the code by hand, line by line, writing down what each variable holds. This lesson walks through the reading log that way.

Both source files declare package main. The compiler builds them together, so main can call parseSession and totalMinutes from log.go. Each file declares the imports it uses.

One package, several files

A Go package is a folder of files that share a package name. Everything declared at the top level of one file, such as a type, a function or a variable, is visible in every other file of the same package, with no import needed. Imports are different: they belong to a single file. log.go imports strconv because it converts minutes, and main.go does not, because it never calls strconv itself. Go would report an unused import in main.go if it did.

Follow the sample, line by line

The sample input has four lines. Here is what happens to each, starting from lineNumber := 0 and an empty sessions slice:

  1. Poems,25 is parsed and appended. lineNumber is 1, and the slice holds 1 session.
  2. Essays,0 is rejected and its message is printed. lineNumber is 2; the slice still holds 1 session.
  3. The blank line is skipped before parsing. lineNumber is 3; still 1 session.
  4. Short stories,35 is parsed and appended. lineNumber is 4, and the slice holds 2 sessions.

Notice that lineNumber goes up on every line, even blank and rejected ones, while the slice grows only for accepted sessions. The two numbers answer different questions. One says where a line was in the input, the other how many records the report will contain.

Trace the reading log Go
package main import ( "bufio" "fmt" "os" "strings" ) func main() { scanner := bufio.NewScanner(os.Stdin) var sessions []Session lineNumber := 0 for scanner.Scan() { lineNumber++ line := scanner.Text() if strings.TrimSpace(line) == "" { continue } session, err := parseSession(line) if err != nil { fmt.Printf("Line %d: %s\n", lineNumber, err) continue } sessions = append(sessions, session) } if err := scanner.Err(); err != nil { fmt.Fprintln(os.Stderr, "Input error:", err) return } fmt.Println("Reading log") for _, session := range sessions { fmt.Printf("%s: %d min\n", session.Title, session.Minutes) } fmt.Printf("Sessions: %d | Minutes: %d\n", len(sessions), totalMinutes(sessions)) } package main import ( "errors" "strconv" "strings" ) type Session struct { Title string Minutes int } func parseSession(line string) (Session, error) { title, rawMinutes, ok := strings.Cut(line, ",") if !ok { return Session{}, errors.New("use title,minutes") } title = strings.TrimSpace(title) if title == "" { return Session{}, errors.New("title is required") } minutes, err := strconv.Atoi(strings.TrimSpace(rawMinutes)) if err != nil || minutes < 1 || minutes > 240 { return Session{}, errors.New("use 1–240 whole minutes") } return Session{Title: title, Minutes: minutes}, nil } func totalMinutes(sessions []Session) int { total := 0 for _, session := range sessions { total += session.Minutes } return total } Poems,25 Essays,0 Short stories,35

Inside parseSession

For line 2, strings.Cut finds the comma, so title is Essays and the raw minutes are 0. The title is not blank after trimming, so that check passes. strconv.Atoi converts 0 without an error, but minutes < 1 is true, so the function returns an empty Session and the error use 1–240 whole minutes. Back in main, err is not nil, so the message is printed with its line number and continue skips the append.

Trace with the code, not from memory

Keep the editor open beside your notes and point at each line as you trace it. It is easy to trace the program you think was written instead of the one that is there, and that gap is exactly where bugs live.

Exercise

Trace two input lines

Follow the second and fourth lines from the scanner through the parser. Explain when a record is appended and how a blank line affects the reported line numbers.

Hint 1: the idea

Track line number and accepted record count separately.

Hint 2: a first step

Find where lineNumber is incremented relative to the blank-line and error checks.

Worked solution

The second line is parsed but rejected because zero is outside the range. The loop continues without appending anything. The third line increments lineNumber and is skipped before parsing. The fourth line passes validation and is appended. Line numbers describe the input, while the session count describes the accepted records.

Where would a change go?

Tracing also tells you where to make a change. Ask which file owns the behavior:

  • A new validation rule, such as rejecting titles longer than 40 characters, belongs in parseSession in log.go. Every caller then gets it for free, and the checks can cover it.
  • A new line in the report, such as an average, belongs in main.go, next to the other output. The arithmetic itself could be a small function in log.go so it can be checked too.
  • A different input source, such as a file name given on the command line, changes only main.go. The rules do not care where a line came from.

When a change seems to need edits in both files at once, that is often a sign the work can be split into a rule, which goes in log.go, and its presentation, which goes in main.go.

Was this article helpful?

Your response is saved on this device.