Refactoring Go Programs

Guidelines and techniques for evolving your code.

Roger Peppe

Canonical Ltd

Overview

2

What is refactoring?

3

Small scale

4

Large scale

5

Experience

6

Why do we refactor?

7

Examples

8

Go advantage

9

Renaming a function

func foo(x int) {
}

renaming to:

func bar(x int) {
}
10

Renaming a function

func Foo(x int) {
}

renaming to:

func Bar(x int) {
}
11

Renaming a function

12

Leverage the compiler

13

Factor functions into methods.

func x(i int) string {
    return y("something", i)
}
func y(s string, n int) string {
    return s + strings.Repeat("foo", i))
}

->

type repeater struct {
    count int
}
func (r *repeater) x(i int) string {
    r.count++
    return y("something", i)
}
func (r *repeater) y(i int, s string) string {
    r.count++
    return s + strings.Repeat("foo", i))
}
14

Factor methods into functions

func x(i int, c counter) string {
    c.inc()
    return y(i, c)
}
15

Tools for bulk code change (1)

gofmt -w -r 'Foo(x, y) -> Foo(x, y, nil)' .
16

Tools for bulk code change (2)

17

Tools for bulk code change (3)

sam -d *.go
18

Tools for bulk code change (3)

govers -m github.com/foo/bar github.com/me/bar
19

Tools for bulk code change (4)

20

Tools for bulk code change (5)

e.g.

if err := foo(bar); err != io.EOF {
    return err
}

->

if err := foo(bar); errgo.Cause(err) != io.EOF {
    return errgo.Mask(err)
}
21

Obstacles

22

Reflection

23

Tests

24

Inconsistency

25

Excess interfaces

26

The future?

27

Thank you

Roger Peppe

Canonical Ltd

Use the left and right arrow keys or click the left and right edges of the page to navigate between slides.
(Press 'H' or navigate to hide this message.)