Skip to content

Instantly share code, notes, and snippets.

@jochasinga
Last active May 31, 2016 14:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jochasinga/d5d2cf721d0d550956ac37eebb4e6ad8 to your computer and use it in GitHub Desktop.
Save jochasinga/d5d2cf721d0d550956ac37eebb4e6ad8 to your computer and use it in GitHub Desktop.
Example of dependency injection in action
package di
import (
"fmt"
"regexp"
)
// This is a pretty dumb function. It can only works
// if you want to stay with "Hello" forever.
func PrintIfMatchedHello(msg string) {
if msg == "Hello" {
fmt.Println(msg)
}
}
// Better, but still quite dumb.
func PrintIfMatchedString(msg, matcher string) {
if msg == matcher {
fmt.Println(msg)
}
}
// You might think regex is the way
func PrintIfMatchedPattern(msg, pattern string) {
matched, err := regexp.MatchString(pattern, msg)
if err != nil {
panic(err)
}
if matched {
fmt.Println(msg)
}
}
// But, hey, Go has a first-class function! Why not
// go for a full inversion of control?
func PrintIfMatched(msg string, matcher func(string) bool) {
if matcher(msg) {
fmt.Println(msg)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment