Created
October 15, 2014 21:15
-
-
Save christophberger/f6f8dc96a28d7fa52ec6 to your computer and use it in GitHub Desktop.
Functional Options 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
// Functional Options | |
// Written to help me wrapping my brains around Functional Options - see this | |
// blog post about a speech by Dave Cheney: | |
// http://dotgo.sourcegraph.com/post/99643162983/dave-cheney-functional-options | |
// | |
// The idea behind Functional Options: | |
// How to add options to an API later without breaking the API? | |
// Solution: | |
package main | |
import ( | |
"errors" | |
"fmt" | |
"time" | |
) | |
// Message contains two options, Level and Timestamp. | |
// Below we will define functions for setting these two options. | |
type Message struct { | |
msg string | |
level int | |
useTs bool | |
} | |
// Set sets the message sting and any options passed in. | |
func (m *Message) Set(msg string, options ...func(*Message) error) { | |
m.msg = msg | |
m.level = 0 | |
m.useTs = false | |
m.setOptions(options...) | |
} | |
// Send sends the message. | |
func (m *Message) Send() { | |
if m.useTs { | |
t := time.Now() | |
fmt.Printf("%v ", t.UTC().Format("2006-01-02 15:04:05.000")) | |
} | |
levels := [5]string{"Fatal", "Error", "Warning", "Info", "Debug"} | |
fmt.Printf("(%v) %v\n", levels[m.level], m.msg) | |
} | |
// SetOptions takes one or more option functions and calls each of them. | |
// Each option function can then apply its option to the receiver. | |
func (m *Message) setOptions(options ...func(*Message) error) error { | |
for _, option := range options { | |
err := option(m) | |
if err != nil { | |
return err | |
} | |
} | |
return nil | |
} | |
// Level is an option function for Message. It returns a function that sets | |
// the severity level of the message. | |
func Level(lvl int) func(m *Message) error { | |
return func(m *Message) error { | |
if lvl < 0 || lvl > 4 { | |
return errors.New("Level must be between 0 and 5.") | |
} | |
m.level = lvl | |
return nil | |
} | |
} | |
// UseTimestamp is an option function for Message. Unlike Level(), it does | |
// not create and return a function. Rather, because it represents a | |
// boolean option, it has no parameters and thus already has the signature | |
// of an option function. Just pass it to the initializer function. | |
// UseTimestamp sets useTs to true. | |
// If useTs is true, Send() adds a timestamp to the message. | |
func UseTimestamp(m *Message) error { | |
m.useTs = true | |
return nil | |
} | |
// Add your option function here. | |
// Add a private option member to the Message type. | |
// No need to change the Set() function in any way. Message's API remains stable! | |
// func MyOption(p MyParam) func(m *Message) error { | |
// ... | |
//} | |
func main() { | |
msg := &Message{} | |
msg.Set("Test message", Level(3), UseTimestamp) | |
msg.Send() | |
msg.Set("Another test message", Level(4)) | |
msg.Send() | |
msg.Set("Panic!") | |
msg.Send() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The best way to understand a programming concept is to write a pice of code that demonstrate that concept. I stumbled over Functional Option via the blog post mentioned in the package comment and wrote this to understand how Functional Options work.
This code is "go runable".
License:
Copyright (c) 2015, Christoph Berger code@christophberger.com
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
list of conditions and the following disclaimer.
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
may be used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.