Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 62 additions & 0 deletions projects/interfaces/IMPLEMENTATION.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
# Implementation of interfaces project

## How to run

The primary artifacts of this project are a struct implementation, and a series of tests.

To run the tests for this project, `cd` to this directory and run `go test ./...`. You should see all the tests pass.

## Comparing the tests

There are two different implementations of this test suite.

In [`buffer_table_test.go`](./buffer_table_test.go) there is a table-driven test. In [`buffer_test.go`](./buffer_test.go) there is a non-table-driven test.

Often we use [table-driven tests](https://dave.cheney.net/2019/05/07/prefer-table-driven-tests) in Go because they make it easy to do similar things many times (factoring out commonality to be [DRY](https://en.wikipedia.org/wiki/Don%27t_repeat_yourself)), and make it really easy to add extra test-cases.

In this example, it's not obvious that table-driven tests are better than non-table-driven tests. Take a bit of time to look at both tests and think about the trade-offs involved here:
* Which set of tests would you prefer to write?
* Which set of tests would you prefer to read?
* Which set of tests would you prefer to maintain?

Think about this yourself before reading the next section.

### Advantages of non-table-driven tests

In this example, the table-driven tests are harder to read and verify they're obviously correct.

In the non-table-driven tests, each test reads top-to-bottom quite clearly.

In the table-driven tests, you need to understand quite a lot about the `operations` field. If you want to verify the exact behaviours, you need to read several interface implementations, and understand how they interact.

We don't often write tests for our tests, so in tests, we strongly value being able to see that they're obviously correct just by reading them. One could argue that the non-table-driven test does this better, in this example.

### Advantages of table-driven tests

#### Adding more tests

In this example, the table-driven tests are more re-usable. If we wanted to add lots more tests with different permutations ("write then read then write again then write again then read"), it would be easier to add these extra tests in the table-driven way. Making it easy to write more tests is generally a good thing.

#### Changing all the tests

Imagine we changed the implementation of our buffer (e.g. added an `error` return to some function, or changed how we construct a buffer). In the table-driven tests, we only have a few actual uses of the buffer API - probably one per `operation` implementation.

In the non-table-driven test version, we need to make that change in lots of places. By avoiding repeating ourselves and factoring away the commonality, we reduced the number of places we need to change our tests if something changes in our implementation.

### Summary

Neither approach is obviously _better_. They have different trade-offs. This is a common situation when writing software.

If we were testing something a little simpler, like testing the `FilteringPipe` type, the tests would have fewer differences between them (e.g. just differing in what's written, rather than having lots of different operations), a table-driven test would probably be a more obvious winner.

We need to choose what we're optimising for: Are we optimising for making it easy to add lots more complex ordering tests? Are we optimising for making it easy to read and verify the test works? How do we imagine needing to change the code in the future, and what will make _that_ easy?

## Implementation notes on `OurByteBuffer`

#### Struct vs Pointer

When implementing a method on a struct, we can choose to implement it on the struct type itself (`func (b OurByteBuffer) someMethod()`) or on a pointer to the struct type (`func (b *OurByteBuffer) someMethod()`).

We chose to implement the methods on a pointer to the struct, rather than just the struct.

This is because we have information which we need to be preserved across the different methods. If we implemented the methods on the struct, each call to `Write` would get a new copy of `OurByteBuffer`, so when we update `b.bytes` it would only get updated _in that copy_.
33 changes: 33 additions & 0 deletions projects/interfaces/buffer.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package main

type OurByteBuffer struct {
bytes []byte
readPosition int
}

func NewBufferString(s string) OurByteBuffer {
return OurByteBuffer{
bytes: []byte(s),
readPosition: 0,
}
}

func (b *OurByteBuffer) Bytes() []byte {
return b.bytes
}

func (b *OurByteBuffer) Write(bytes []byte) (int, error) {
b.bytes = append(b.bytes, bytes...)
return len(bytes), nil
}

func (b *OurByteBuffer) Read(to []byte) (int, error) {
remainingBytes := len(b.bytes) - b.readPosition
bytesToRead := len(to)
if remainingBytes < bytesToRead {
bytesToRead = remainingBytes
}
copy(to, b.bytes[b.readPosition:b.readPosition+bytesToRead])
b.readPosition += bytesToRead
return bytesToRead, nil
}
102 changes: 102 additions & 0 deletions projects/interfaces/buffer_table_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
package main

import (
"testing"

"github.com/stretchr/testify/require"
)

func TestOurByteBuffer_Table(t *testing.T) {
for name, tc := range map[string]struct {
initialContent string
operations []operation
}{
"read_initial_bytes": {
initialContent: "hello",
operations: []operation{
&bytesOperation{
wantValue: "hello",
},
},
},
"subsequent_writes_are_appended": {
initialContent: "hello",
operations: []operation{
&writeOperation{
value: " world",
},
&bytesOperation{
wantValue: "hello world",
},
},
},
"read_oversized_slice": {
initialContent: "hello world",
operations: []operation{
&readOperation{
bufferSize: 50,
wantValue: "hello world",
},
},
},
"read_undersized_slices": {
initialContent: "hello world",
operations: []operation{
&readOperation{
bufferSize: 6,
wantValue: "hello ",
},
&readOperation{
bufferSize: 5,
wantValue: "world",
},
},
},
} {
t.Run(name, func(t *testing.T) {
b := NewBufferString(tc.initialContent)
for _, operation := range tc.operations {
operation.Do(t, &b)
}
})
}
}

type operation interface {
Do(t *testing.T, b *OurByteBuffer)
}

type readOperation struct {
bufferSize int
wantValue string
}

func (o *readOperation) Do(t *testing.T, b *OurByteBuffer) {
t.Helper()
buf := make([]byte, o.bufferSize)
n, err := b.Read(buf)
require.NoError(t, err)
require.Equal(t, len(o.wantValue), n)
require.Equal(t, o.wantValue, string(buf[:n]))
}

type writeOperation struct {
value string
}

func (o *writeOperation) Do(t *testing.T, b *OurByteBuffer) {
t.Helper()
n, err := b.Write([]byte(o.value))
require.NoError(t, err)
require.Equal(t, len(o.value), n)
}

type bytesOperation struct {
wantValue string
}

func (o *bytesOperation) Do(t *testing.T, b *OurByteBuffer) {
t.Helper()
got := string(b.Bytes())
require.Equal(t, o.wantValue, got)
}
57 changes: 57 additions & 0 deletions projects/interfaces/buffer_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
package main

import (
"testing"

"github.com/stretchr/testify/require"
)

func TestInitialBytesAreRead(t *testing.T) {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

could be done as a table driven test, which is better go idiom imo

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could I bother you to sketch out what the per-testcase struct would look like here?

I put together my best guess in buffer_table_test.go, but it feels like quite a bit of added complexity, and like it makes the tests harder to read and interpret. Maybe I'm just not looking at it the right way, and that's not what you had in mind?

want := []byte("hello")

b := NewBufferString("hello")

got := b.Bytes()

require.Equal(t, want, got)
}

func TestSubsequentWritesAreAppended(t *testing.T) {
want := []byte("hello world")

b := NewBufferString("hello")

_, err := b.Write([]byte(" world"))
require.NoError(t, err)

got := b.Bytes()

require.Equal(t, want, got)
}

func TestReadWithSliceBigEnoughForWholeBuffer(t *testing.T) {
b := NewBufferString("hello world")

slice := make([]byte, 50)

n, err := b.Read(slice)
require.NoError(t, err)
require.Equal(t, 11, n)
require.Equal(t, []byte("hello world"), slice[:n])
}

func TestReadWithSliceSmallerThanWholeBuffer(t *testing.T) {
b := NewBufferString("hello world")

slice := make([]byte, 6)

n, err := b.Read(slice)
require.NoError(t, err)
require.Equal(t, 6, n)
require.Equal(t, []byte("hello "), slice)

n, err = b.Read(slice)
require.NoError(t, err)
require.Equal(t, 5, n)
require.Equal(t, []byte("world"), slice[:n])
}
27 changes: 27 additions & 0 deletions projects/interfaces/filtering_pipe.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package main

import (
"io"
)

type FilteringPipe struct {
writer io.Writer
}

func NewFilteringPipe(writer io.Writer) FilteringPipe {
return FilteringPipe{
writer: writer,
}
}

func (fp *FilteringPipe) Write(bytes []byte) (int, error) {
for i := range bytes {
if bytes[i] < '0' || bytes[i] > '9' {
if _, err := fp.writer.Write(bytes[i : i+1]); err != nil {
return i, err
}
}
}
// We return len(bytes) because io.Writer is documented to return how many bytes were processed, not how many were actually used.
return len(bytes), nil
}
45 changes: 45 additions & 0 deletions projects/interfaces/filtering_pipe_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package main

import (
"bytes"
"testing"

"github.com/stretchr/testify/require"
)

func TestFilteringPipe(t *testing.T) {
for name, tc := range map[string]struct {
inputs []string
output string
}{
"no_numbers_in_input": {
inputs: []string{"hello"},
output: "hello",
},
"just_numbers": {
inputs: []string{"123"},
output: "",
},
"mixed_numbers_and_letters": {
inputs: []string{"start=1, end=10"},
output: "start=, end=",
},
"multiple_writes": {
inputs: []string{"start=", "1, end=10"},
output: "start=, end=",
},
} {
t.Run(name, func(t *testing.T) {
buf := bytes.NewBufferString("")

fp := NewFilteringPipe(buf)

for _, input := range tc.inputs {
n, err := fp.Write([]byte(input))
require.NoError(t, err)
require.Equal(t, len(input), n)
}
require.Equal(t, tc.output, buf.String())
})
}
}
10 changes: 10 additions & 0 deletions projects/interfaces/go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
module github.com/CodeYourFuture/immersive-go-course/projects/interfaces

go 1.19

require (
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/stretchr/testify v1.8.2 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)
16 changes: 16 additions & 0 deletions projects/interfaces/go.sum
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
github.com/stretchr/testify v1.8.2 h1:+h33VjcLVPDHtOdpUCuF+7gSuG3yGIftsP1YvFihtJ8=
github.com/stretchr/testify v1.8.2/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=