Last active
October 30, 2024 07:31
-
-
Save rednafi/08fe371ed31072ab0bd96bf51611660a to your computer and use it in GitHub Desktop.
Dysfunctional option pattern in Go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package src | |
import ( | |
"testing" | |
) | |
// Apply functional options pattern | |
type config struct { | |
// Required | |
foo, bar string | |
// Optional | |
fizz, buzz int | |
} | |
type option func(*config) | |
func WithFizz(fizz int) option { | |
return func(c *config) { | |
c.fizz = fizz | |
} | |
} | |
func WithBuzz(buzz int) option { | |
return func(c *config) { | |
c.buzz = buzz | |
} | |
} | |
func NewConfig(foo, bar string, opts ...option) *config { | |
c := &config{foo: foo, bar: bar} | |
for _, opt := range opts { | |
opt(c) | |
} | |
return c | |
} | |
// Benchmark the functional options pattern | |
func BenchmarkNewConfig(b *testing.B) { | |
b.ReportAllocs() | |
for i := 0; i < b.N; i++ { | |
NewConfig("foo", "bar", WithFizz(1), WithBuzz(2)) | |
} | |
} | |
// Dysfunctional options pattern | |
type configDys struct { | |
// Required | |
foo, bar string | |
// Optional | |
fizz, buzz int | |
} | |
func NewConfigDys(foo, bar string) *configDys { | |
return &configDys{foo: foo, bar: bar} | |
} | |
func (c *configDys) WithFizz(fizz int) *configDys { | |
c.fizz = fizz | |
return c | |
} | |
func (c *configDys) WithBuzz(buzz int) *configDys { | |
c.buzz = buzz | |
return c | |
} | |
// Benchmark the dysfunctional options pattern | |
func BenchmarkNewConfigDys(b *testing.B) { | |
b.ReportAllocs() | |
for i := 0; i < b.N; i++ { | |
NewConfigDys("foo", "bar").WithFizz(1).WithBuzz(2) | |
} | |
} |
My analog test with result:
go test -bench=. -benchtime=100s
goos: linux
goarch: amd64
pkg: internal/testutil/project
cpu: Intel(R) Core(TM) i7-8565U CPU @ 1.80GHz
BenchmarkFuncOptions-8 36885484 3613 ns/op 336 B/op 2 allocs/op
BenchmarkDisfuncOptions-8 44132131 2549 ns/op 344 B/op 3 allocs/op
PASS
ok internal/testutil/project 345.614s
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Here's the result (ran on a macbook air 15 inch, 16-256 config)