Skip to content

Instantly share code, notes, and snippets.

@s4cha
Last active April 5, 2022 23:08
Show Gist options
  • Save s4cha/404f0f9530d0589ce71aa67e956b8c33 to your computer and use it in GitHub Desktop.
Save s4cha/404f0f9530d0589ce71aa67e956b8c33 to your computer and use it in GitHub Desktop.
Dependency inversion in go
package main
func main() {
// Create our dependency.
lf := FileLinkFetcher{}
// lf := DatabaseLinkFetcher{}
// Here we "inject" the fileLinkFetcher in the App constructor.
app := App{linkFetcher: lf}
app.run()
}
/* App Code */
type App struct {
linkFetcher LinkFetcher // App only knows (aka depends) on an interface \o/
}
func (app *App)run() {
println("Running Application")
app.linkFetcher.fetchLinks()
println("Processing Links...")
println("Ending Application")
}
/// Strong LinkFetcher interface
type LinkFetcher interface {
fetchLinks()
}
/* End App Code */
/*
Depndedencies, aka Injected from main
Ideally this lives a another package / file
*/
/// This is our concrete implementation of the LinkFetcher interface.
type FileLinkFetcher struct { }
/// Here we implement linkFetcher interface
/// to fetch links from a file.
func (lf FileLinkFetcher)fetchLinks() {
println("Fetching Links from a file...")
}
/// Here is how simple it is to provide an database version!
type DatabaseLinkFetcher struct { }
func (lf DatabaseLinkFetcher)fetchLinks() {
println("Fetching Links from a database...")
}
/// Instead of App depending on FileLinkFetcher
/// App -----> FileLinkFetcher
/// We now have App depending on <LinkFetcher>
/// And FileLinkFetcher depending on <LinkFetcher>
/// App -----> <LinkFetcher> <----- FileLinkFetcher
/// We just inverted the dependency! \o/
/// Notes:
/// App "depends" on LinkFetcher interface, which is ours, so it's not considered a dependency for app.
/// And now the Implementation detail (the fact that its from a file) has to obey to OUR rules.
/// The idea behnd this is WE MAKE THE RULES for OUR APP.
/// the details must abide by our rules and are "injected" from the main.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment