Putting it together: a command-line program

Intermediate

Introduction

You now know the main parts of Go: variables, control flow, functions, slices, maps, strings, structs, methods, interfaces and errors. This last lesson puts them together in one small but complete program, a task manager that you control with commands. Real programs are built the same way, only bigger. The skill to practise now is design: deciding what the data is, what actions change it, and how to keep each part of the program simple.

How it works

A good way to plan a program is to ask three questions. What is the data? Here it is a list of tasks, each with a number, a text and a done flag. What can happen to it? Add a task, mark one done, list the tasks, count them. What can go wrong? A task number that does not exist, or an unknown command. The answers become the code.

First the types. A Task struct holds the fields, and a Manager struct holds the list and the next number:

type Task struct {
	ID   int
	Text string
	Done bool
}

type Manager struct {
	tasks  []Task
	nextID int
}

Then the methods. Each one does one job on the manager and returns an error if it cannot. Add(text) appends a task, Complete(id) finds the task and returns an error when there is none, and Counts() returns the number of open and done tasks. These methods do not read input or print anything. That is the separation of concerns: the rules live in the methods, and main takes care of input and output. The methods can then be tested on their own and reused.

Finally the command loop in main. It reads lines with a bufio.Scanner, splits each line with strings.Fields, and chooses what to do with a switch on the first word:

for scanner.Scan() {
	fields := strings.Fields(scanner.Text())
	switch fields[0] {
	case "add":
		m.Add(strings.Join(fields[1:], " "))
	case "done":
		// convert fields[1] and call m.Complete
	}
}

Each case reads its arguments, calls a method, and prints what happened. If a method returns an error, main prints the message and goes on to the next command; it does not stop. Check the input before using it: an empty line has no first word, and a command may have a missing or wrong argument.

When you build your own program, work in small steps. Write the types and print one value. Add one command and test it. Add the next. Keep every function short, and name things after what they mean.

Example

package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
	"strings"
)

type Task struct {
	ID   int
	Text string
	Done bool
}

type Manager struct {
	tasks  []Task
	nextID int
}

func NewManager() *Manager {
	return &Manager{nextID: 1}
}

func (m *Manager) Add(text string) int {
	t := Task{ID: m.nextID, Text: text}
	m.tasks = append(m.tasks, t)
	m.nextID++
	return t.ID
}

func (m *Manager) Complete(id int) error {
	for i := range m.tasks {
		if m.tasks[i].ID == id {
			m.tasks[i].Done = true
			return nil
		}
	}
	return fmt.Errorf("no task %d", id)
}

func (m *Manager) Counts() (open, done int) {
	for _, t := range m.tasks {
		if t.Done {
			done++
		} else {
			open++
		}
	}
	return
}

func main() {
	m := NewManager()
	scanner := bufio.NewScanner(os.Stdin)
	for scanner.Scan() {
		fields := strings.Fields(scanner.Text())
		if len(fields) == 0 {
			continue
		}
		switch fields[0] {
		case "add":
			id := m.Add(strings.Join(fields[1:], " "))
			fmt.Println("added", id)
		case "done":
			if len(fields) < 2 {
				fmt.Println("error: done needs a number")
				continue
			}
			id, err := strconv.Atoi(fields[1])
			if err != nil {
				fmt.Println("error: not a number")
				continue
			}
			if err := m.Complete(id); err != nil {
				fmt.Println("error:", err)
			}
		case "list":
			for _, t := range m.tasks {
				mark := " "
				if t.Done {
					mark = "x"
				}
				fmt.Printf("[%s] %d %s\n", mark, t.ID, t.Text)
			}
		case "count":
			open, done := m.Counts()
			fmt.Printf("open: %d, done: %d\n", open, done)
		default:
			fmt.Println("unknown command:", fields[0])
		}
	}
}

Input used: add buy milk ⏎ add write code ⏎ done 1 ⏎ done 7 ⏎ list ⏎ count ⏎ dance

Line by line

  1. Task and Manager hold the data. NewManager makes a manager that numbers tasks from 1.
  2. Add appends a task and returns its number. Complete looks for the task and returns an error if there is none. Counts counts open and finished tasks.
  3. main reads the commands with a scanner, skips empty lines and splits each line into words.
  4. The switch runs the right method. add joins the rest of the line into the task text, done converts the number with strconv.Atoi, and list prints each task with a mark.
  5. Problems such as a missing task or an unknown command are printed as messages, and the loop carries on.

Expected result

With this input:

add buy milk
add write code
done 1
done 7
list
count
dance

it prints:

added 1
added 2
error: no task 7
[x] 1 buy milk
[ ] 2 write code
open: 1, done: 1
unknown command: dance

In the real world

Tools such as a notes app, a build system or a database shell are all command loops over some data. They keep a clear model, validate everything the user sends, and report errors without crashing. The same structure grows into a web service: the commands become web requests, and the methods stay the same. Programs that are split into small types and functions are much easier to test, change and share with a team.

Common mistakes

  • Putting everything into main, so nothing can be reused or tested.
  • Trusting the input: a missing argument or a text instead of a number stops the program.
  • Printing inside the methods that hold the rules, which mixes two jobs.
  • Stopping at the first error when a command loop should continue.
  • Writing the whole program before running any of it.

Best practices

  • Design the types first, then the methods, then the loop.
  • Return errors from methods and decide in main how to show them.
  • Test after every small step with a short input.
  • Choose names that say what a thing is or does.

Summary

A complete program starts from its data and the actions on it. Structs hold the state, methods change it and return errors, and a command loop in main reads input, dispatches with a switch and prints results. Keeping rules, input and output apart makes the program clear, testable and easy to extend.

Quick check

1. What is the best first step when planning a small program?
2. Why should the methods not print?
3. What should a command loop do when a command fails?
4. Which statement is a natural way to choose the code for each command word?
5. Why check len(fields) before reading fields[0]?

Key takeaways

  • Start with the data: define the types, then the methods that change them.
  • A command loop with a switch keeps main short and easy to read.
  • Methods return errors; main decides how to show them to the user.

Practice problems for this lesson

Was this lesson clear?

My notes

Write down what you want to remember from this lesson. Notes are saved on this device as you type, and appear on your dashboard.