Skip to content

Instantly share code, notes, and snippets.

@benbjohnson
Created March 3, 2014 03:17
Show Gist options
  • Save benbjohnson/9317851 to your computer and use it in GitHub Desktop.
Save benbjohnson/9317851 to your computer and use it in GitHub Desktop.
Application-side Interfaces in Go

Application-side Interfaces in Go

By moving the interface to the application-side (application.go), you can still set the implementation-specific configuration details when you instantiate your library structs. If the interface was implemented on the library-side then you would need to provide:

type DB interface {
  Get([]byte) ([]byte, error)
  Put([]byte, []byte) error
  CacheSize() int
  SetCacheSize(int)
  TurboMode() bool
  SetTurboMode(bool)
}

The extra configuration functions are implementation specific. The generalization of DBs occurs on the application-side (not the library-side) so it makes more sense to only specify the interface required by the application on the application-side.

package myapp
import "mylib"
// DB is a generic interface to a key/value store.
type DB interface {
Get(key []byte) ([]byte, error)
Put(key, value []byte) error
}
// Server represents a wrapper for accessing the DB (maybe over HTTP?).
type Server struct {
db DB
}
func (s *Server) ListenAndServe() error {
...
}
func main() {
// Initialize the specific implementation of DB that we want to use.
db: &mylib.AwesomeDB{
CacheSize: 1024,
TurboMode: true,
}
// Attach it to the server.
s := &Server{db: db}
// Start the server.
s.ListenAndServe()
}
package mylib
type AwesomeDB struct {
CacheSize int
TurboMode bool
}
func (db *DB) Get(key []byte) ([]byte, error) {
...
}
func (db *DB) Put(key, value []byte) error {
...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment