Chapter 5. Packages and Modules in Go
Go programs are constructed by linking together packages. A Go package in turn is constructed from one or more source files...
In this chapter, we’ll do a few things that clean up our Go code. We’ll look at the Go module we created back in Chapter 0 and see its purpose in separating code. Then we’ll do the work to separate our test code from our production code using packages. Finally, we’ll remove some redundancy from our code, making things compact and meaningful.
Separating Our Code into Packages
Let’s begin by separating our test code from our production code. This entails two separate tasks:
-
Separating test code from production code.
-
Ensuring the dependency is only from the test code to the production code.
We have production code for Money
and Portfolio
sitting next to our test code in one file—money_test.go
. Let’s first create two new files named money.go
and portfolio.go
. We’ll put both these files in the $TDD_PROJECT_ROOT/go
folder. Next, we move code for the relevant classes, Money
and Portfolio
, to their appropriate files. This is how portfolio.go
looks:
package
main
type
Portfolio
[]
Money
func
(
p
Portfolio
)
Add
(
money
Money
)
Portfolio
{
p
=
append
(
p
,
money
)
return
p
}
func
(
p
Portfolio
)
Evaluate
(
currency
string
)
Money
{
total
:=
0.0
for
_
,
m
:=
range
p
{
total
=
total
+
m
.
amount
}
return
Money
{
amount
:
total
,
currency
:
currency
}
}
The file money.go
, not shown here, similarly contains ...
Get Learning Test-Driven Development now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.