Last active
May 31, 2016 14:33
-
-
Save jochasinga/d5d2cf721d0d550956ac37eebb4e6ad8 to your computer and use it in GitHub Desktop.
Example of dependency injection in action
This file contains hidden or 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 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