SlideShare a Scribd company logo
1 of 21
Download to read offline
Interface All The Things
12 May 2015
Jonathan Gomez
Engineer, Zumata
Overview
What are interfaces?
Why they are awesome?
Tips / Gotchas
Illustrate via examples
Intro to Interfaces
typeGopherinterface{
Nod()
Wink()
}
Could be read as, a Gopheris something that has these behaviours / actions:
Ability to nod
Ability to wink
Intro to Interfaces
Lets implement Nod()and Wink():
typeSingGopherstruct{}
func(g*SingGopher)Nod(){
fmt.Println("cannod")
}
func(g*SingGopher)Wink(){
fmt.Println("winkalsocan")
}
By having these methods, SingGopherimplicitly satisfies the Gopherinterface.
i.e. don't need to explicitly state that SingGopherimplements the interface.
Intro to Interfaces
With the interface satisfied, we can assign our SingGopherto the Gophertype.
funcplay(gopherGopher){
gopher.Nod()
gopher.Wink()
}
funcmain(){
play(&SingGopher{})
} Run
Intro to Interfaces
What if a method was missing?
Think in terms of method sets: set of interface ⊆ set of concrete type
funcmain(){
play(&SingGopher{})
} Run
Why use interfaces?
Why use interfaces? Abstract and avoid repetition
e.g. Gopherprocessing code (business logic)
funcpipeline(gophers...Gopher){
for_,gopher:=rangegophers{
play(gopher)
}
}
As new gophers are added, no change is required.
Note: Can define functions and methods that take interfaces, but can't define
methods on the interface (e.g. gopher.Play())
funcmain(){
pipeline(&SingGopher{},&YodaGopher{})
} Run
Why use interfaces? Combine simple units to achieve complexity
Example of standard library's io.Readerinterface:
typeReaderinterface{
Read(p[]byte)(nint,errerror)
}
Functions/methods that take io.Readerarguments are indifferent to where data
is coming from. e.g. os.File, bytes.Buffer, net.Conn, http.Request.Body
//json
funcNewDecoder(rio.Reader)*Decoder
//gzip
funcNewReader(rio.Reader)(*Reader,error)
Chain for complexity:
response,_:=client.Do(request)
raw,_:=gzip.NewReader(response.Body)
json.NewDecoder(raw).Decode(&data)
Why use interfaces? Sharing patterns
Dropbox has a interesting caching library @ github.com/dropbox/godropbox
(https://godoc.org/github.com/dropbox/godropbox/caching)
Patterns of caching / managing storage
funcNewCacheOnStorage(cache,storageStorage)Storage
funcNewRateLimitedStorage(storageStorage,maxConcurrencyint)Storage
Developers gain access via implementing Storageon their own:
typeStorageinterface{
Get(...)(interface{},error)
Set(...)error
Delete(...)error
...
}
Tap into / contribute to the growing set of community resources
Why use interfaces? Testing
If our functions have interface args, we can test them with mock implementations
i.e. use a FakeGopherto test our code that depends on Gopher
typeFakeGopherstruct{
Noddedbool
Winkedbool
}
func(g*FakeGopher)Nod(){
g.Nodded=true
}
func(g*FakeGopher)Wink(){
g.Winked=true
}
funcTestPlay(){
g:=&FakeGopher{}
g.ShowState()
play(g)
g.ShowState()
} Run
Why use interfaces? Flexibility to change your lib/infra decisions
In one of our apps, we use a 3rd party logging library, logrus.
Avoid our codebase being coupled to it, by having an interface for logging.
typeLoggerinterface{
Info(args...interface{})
Warn(args...interface{})
Error(args...interface{})
Infof(args...interface{})
Warnf(args...interface{})
Errorf(args...interface{})
}
e.g. Publisherw/ Publish()(to queue) & Mailer& Mail()(3rd party service)
Seize opportunities to decrease coupling / increase options.
Better to do earlier than later.
Why use interfaces? Flexibility for package consumers
typeStorageinterface{
Get(...)(Kites,error)
Add(...)error
Update(...)error
Delete(...)error
Upsert(...)error
}
Interesting microservices project github.com/koding/kite(https://github.com/koding/kite)
Storageinterface with Postgresand Etcdimplementations
Useful here to give the consumer options
Maybe unnecessary in your own app
Why use interfaces? Very natural fit for some problems
When standardisation is essential to design
The method set creates the standard
Project to create and manage Docker hosts across providers
github.com/docker/machine(https://github.com/docker/machine)
typeDriverinterface{
Create()error
GetIP()(string,error)
Start()error
Stop()error
...
}
Implementations for Amazon, Google, Digital Ocean, Azure, OpenStack, Rackspace
+
Tips: Check out the standard library
100+ interfaces
error
Stringer
Handler
ResponseWriter
sort.Interface
Reader,Writer,ReadWriter,
Marshaler,Umarshaler
TB(tests,benchmarks)
Convention is to name the one method interface Method-er
Encouragement to keep interfaces small, but it isn't a hard rule
Smaller = less work to satisfy
Where your code can be compatible with standard library / community interfaces,
will be more easily useable by others
e.g. middleware that takes a Handlerand returns a Handler
Tips: Use embedding to keep interfaces small
Compose larger interfaces out of smaller ones
typeReaderinterface{
Read(p[]byte)(nint,errerror)
}
typeWriterinterface{
Write(p[]byte)(nint,errerror)
}
typeReadWriterinterface{
Reader
Writer
}
When method invoked, the receiver is the inner type, not outer
Will reduce code complexity, encourage simpler implementations
Tips: Type assert for accessing different functionality
Assume some gophers are also coders which can Code()
typeCoderinterface{
Code()
}
Runtime type assert to see whether the Gopheris a Coder& call Code()
funcwriteCode(gopherGopher){
//ifourGophersatisfiesCoder,thentypeassert
ifcoder,ok:=gopher.(Coder);ok{
coder.Code()
}
}
Note: the coder can't call Nod()or Wink().
Considered an idiom in Go to convert type to access different methods.
Tips: Interfaces and nil
What is an interface? Implemented as a type and a value
If type is set, and value is a nil pointer, the interface is not nil
When implementing custom errors - return nil instead of interfaces with nil values.
funcmain(){
varsingGopher*SingGopher
vargopherGopher
vargopher2Gopher=singGopher
fmt.Println("values:")
fmt.Println("singGopher:",singGopher,singGopher==nil)
fmt.Println("gopher:",gopher,gopher==nil)
fmt.Println("gopher2:",gopher2,gopher2==nil)
fmt.Println("types:")
fmt.Printf("singGopher:%#vn",singGopher)
fmt.Printf("gopher:%#vn",gopher)
fmt.Printf("gopher2:%#vn",gopher2)
} Run
Within reason...
Thank you
Jonathan Gomez
Engineer, Zumata
jonathanbgomez@gmail.com(mailto:jonathanbgomez@gmail.com)
@jonog(http://twitter.com/jonog)

More Related Content

What's hot

Functional programming for production quality code
Functional programming for production quality codeFunctional programming for production quality code
Functional programming for production quality codeJack Fox
 
Java 8 - Lambdas and much more
Java 8 - Lambdas and much moreJava 8 - Lambdas and much more
Java 8 - Lambdas and much moreAlin Pandichi
 
46630497 fun-pointer-1
46630497 fun-pointer-146630497 fun-pointer-1
46630497 fun-pointer-1AmIt Prasad
 
Python Programming Essentials - M6 - Code Blocks and Indentation
Python Programming Essentials - M6 - Code Blocks and IndentationPython Programming Essentials - M6 - Code Blocks and Indentation
Python Programming Essentials - M6 - Code Blocks and IndentationP3 InfoTech Solutions Pvt. Ltd.
 
Python programming workshop session 1
Python programming workshop session 1Python programming workshop session 1
Python programming workshop session 1Abdul Haseeb
 
Python workshop session 6
Python workshop session 6Python workshop session 6
Python workshop session 6Abdul Haseeb
 

What's hot (8)

Generic programming
Generic programmingGeneric programming
Generic programming
 
Functional programming for production quality code
Functional programming for production quality codeFunctional programming for production quality code
Functional programming for production quality code
 
Java 8 - Lambdas and much more
Java 8 - Lambdas and much moreJava 8 - Lambdas and much more
Java 8 - Lambdas and much more
 
46630497 fun-pointer-1
46630497 fun-pointer-146630497 fun-pointer-1
46630497 fun-pointer-1
 
Python Programming Essentials - M6 - Code Blocks and Indentation
Python Programming Essentials - M6 - Code Blocks and IndentationPython Programming Essentials - M6 - Code Blocks and Indentation
Python Programming Essentials - M6 - Code Blocks and Indentation
 
Python programming workshop session 1
Python programming workshop session 1Python programming workshop session 1
Python programming workshop session 1
 
Python workshop session 6
Python workshop session 6Python workshop session 6
Python workshop session 6
 
C++ programming
C++ programmingC++ programming
C++ programming
 

Similar to Interface All The Things

To GO or not to GO
To GO or not to GOTo GO or not to GO
To GO or not to GOsuperstas88
 
The GO Language : From Beginners to Gophers
The GO Language : From Beginners to GophersThe GO Language : From Beginners to Gophers
The GO Language : From Beginners to GophersAlessandro Sanino
 
Composing an App with Free Monads (using Cats)
Composing an App with Free Monads (using Cats)Composing an App with Free Monads (using Cats)
Composing an App with Free Monads (using Cats)Hermann Hueck
 
Building native Android applications with Mirah and Pindah
Building native Android applications with Mirah and PindahBuilding native Android applications with Mirah and Pindah
Building native Android applications with Mirah and PindahNick Plante
 
Coding in GO - GDG SL - NSBM
Coding in GO - GDG SL - NSBMCoding in GO - GDG SL - NSBM
Coding in GO - GDG SL - NSBMRaveen Perera
 
Building End-to-End Apps Using Typescript
Building End-to-End Apps Using TypescriptBuilding End-to-End Apps Using Typescript
Building End-to-End Apps Using TypescriptGil Fink
 
Introduction to Go programming
Introduction to Go programmingIntroduction to Go programming
Introduction to Go programmingExotel
 
Introduction to Griffon
Introduction to GriffonIntroduction to Griffon
Introduction to GriffonJames Williams
 
The AWT and Swing
The AWT and SwingThe AWT and Swing
The AWT and Swingadil raja
 
Java: Java Applets
Java: Java AppletsJava: Java Applets
Java: Java AppletsTareq Hasan
 
What's new with JavaScript in GNOME: The 2020 edition (GUADEC 2020)
What's new with JavaScript in GNOME: The 2020 edition (GUADEC 2020)What's new with JavaScript in GNOME: The 2020 edition (GUADEC 2020)
What's new with JavaScript in GNOME: The 2020 edition (GUADEC 2020)Igalia
 
Desarrollo para Android con Groovy
Desarrollo para Android con GroovyDesarrollo para Android con Groovy
Desarrollo para Android con GroovySoftware Guru
 
Geeks Anonymes - Le langage Go
Geeks Anonymes - Le langage GoGeeks Anonymes - Le langage Go
Geeks Anonymes - Le langage GoGeeks Anonymes
 
Whoops! where did my architecture go?
Whoops! where did my architecture go?Whoops! where did my architecture go?
Whoops! where did my architecture go?Oliver Gierke
 
Functional programming-advantages
Functional programming-advantagesFunctional programming-advantages
Functional programming-advantagesSergei Winitzki
 
Building End to-End Web Apps Using TypeScript
Building End to-End Web Apps Using TypeScriptBuilding End to-End Web Apps Using TypeScript
Building End to-End Web Apps Using TypeScriptGil Fink
 
Whoops! Where did my architecture go?
Whoops! Where did my architecture go?Whoops! Where did my architecture go?
Whoops! Where did my architecture go?Oliver Gierke
 

Similar to Interface All The Things (20)

To GO or not to GO
To GO or not to GOTo GO or not to GO
To GO or not to GO
 
The GO Language : From Beginners to Gophers
The GO Language : From Beginners to GophersThe GO Language : From Beginners to Gophers
The GO Language : From Beginners to Gophers
 
Unit 7 Java
Unit 7 JavaUnit 7 Java
Unit 7 Java
 
Composing an App with Free Monads (using Cats)
Composing an App with Free Monads (using Cats)Composing an App with Free Monads (using Cats)
Composing an App with Free Monads (using Cats)
 
Building native Android applications with Mirah and Pindah
Building native Android applications with Mirah and PindahBuilding native Android applications with Mirah and Pindah
Building native Android applications with Mirah and Pindah
 
Coding in GO - GDG SL - NSBM
Coding in GO - GDG SL - NSBMCoding in GO - GDG SL - NSBM
Coding in GO - GDG SL - NSBM
 
Building End-to-End Apps Using Typescript
Building End-to-End Apps Using TypescriptBuilding End-to-End Apps Using Typescript
Building End-to-End Apps Using Typescript
 
Introduction to Go programming
Introduction to Go programmingIntroduction to Go programming
Introduction to Go programming
 
Introduction to Griffon
Introduction to GriffonIntroduction to Griffon
Introduction to Griffon
 
The AWT and Swing
The AWT and SwingThe AWT and Swing
The AWT and Swing
 
Java: Java Applets
Java: Java AppletsJava: Java Applets
Java: Java Applets
 
What's new with JavaScript in GNOME: The 2020 edition (GUADEC 2020)
What's new with JavaScript in GNOME: The 2020 edition (GUADEC 2020)What's new with JavaScript in GNOME: The 2020 edition (GUADEC 2020)
What's new with JavaScript in GNOME: The 2020 edition (GUADEC 2020)
 
Desarrollo para Android con Groovy
Desarrollo para Android con GroovyDesarrollo para Android con Groovy
Desarrollo para Android con Groovy
 
Geeks Anonymes - Le langage Go
Geeks Anonymes - Le langage GoGeeks Anonymes - Le langage Go
Geeks Anonymes - Le langage Go
 
Whoops! where did my architecture go?
Whoops! where did my architecture go?Whoops! where did my architecture go?
Whoops! where did my architecture go?
 
Go. Why it goes
Go. Why it goesGo. Why it goes
Go. Why it goes
 
Functional programming-advantages
Functional programming-advantagesFunctional programming-advantages
Functional programming-advantages
 
Building End to-End Web Apps Using TypeScript
Building End to-End Web Apps Using TypeScriptBuilding End to-End Web Apps Using TypeScript
Building End to-End Web Apps Using TypeScript
 
Applets
AppletsApplets
Applets
 
Whoops! Where did my architecture go?
Whoops! Where did my architecture go?Whoops! Where did my architecture go?
Whoops! Where did my architecture go?
 

Recently uploaded

Diploma Engineering Drawing Qp-2024 Ece .pdf
Diploma Engineering Drawing Qp-2024 Ece .pdfDiploma Engineering Drawing Qp-2024 Ece .pdf
Diploma Engineering Drawing Qp-2024 Ece .pdfJNTUA
 
Raashid final report on Embedded Systems
Raashid final report on Embedded SystemsRaashid final report on Embedded Systems
Raashid final report on Embedded SystemsRaashidFaiyazSheikh
 
DBMS-Report on Student management system.pptx
DBMS-Report on Student management system.pptxDBMS-Report on Student management system.pptx
DBMS-Report on Student management system.pptxrajjais1221
 
Basics of Relay for Engineering Students
Basics of Relay for Engineering StudentsBasics of Relay for Engineering Students
Basics of Relay for Engineering Studentskannan348865
 
Involute of a circle,Square, pentagon,HexagonInvolute_Engineering Drawing.pdf
Involute of a circle,Square, pentagon,HexagonInvolute_Engineering Drawing.pdfInvolute of a circle,Square, pentagon,HexagonInvolute_Engineering Drawing.pdf
Involute of a circle,Square, pentagon,HexagonInvolute_Engineering Drawing.pdfJNTUA
 
Seismic Hazard Assessment Software in Python by Prof. Dr. Costas Sachpazis
Seismic Hazard Assessment Software in Python by Prof. Dr. Costas SachpazisSeismic Hazard Assessment Software in Python by Prof. Dr. Costas Sachpazis
Seismic Hazard Assessment Software in Python by Prof. Dr. Costas SachpazisDr.Costas Sachpazis
 
History of Indian Railways - the story of Growth & Modernization
History of Indian Railways - the story of Growth & ModernizationHistory of Indian Railways - the story of Growth & Modernization
History of Indian Railways - the story of Growth & ModernizationEmaan Sharma
 
Circuit Breakers for Engineering Students
Circuit Breakers for Engineering StudentsCircuit Breakers for Engineering Students
Circuit Breakers for Engineering Studentskannan348865
 
Working Principle of Echo Sounder and Doppler Effect.pdf
Working Principle of Echo Sounder and Doppler Effect.pdfWorking Principle of Echo Sounder and Doppler Effect.pdf
Working Principle of Echo Sounder and Doppler Effect.pdfSkNahidulIslamShrabo
 
Theory of Time 2024 (Universal Theory for Everything)
Theory of Time 2024 (Universal Theory for Everything)Theory of Time 2024 (Universal Theory for Everything)
Theory of Time 2024 (Universal Theory for Everything)Ramkumar k
 
Artificial Intelligence in due diligence
Artificial Intelligence in due diligenceArtificial Intelligence in due diligence
Artificial Intelligence in due diligencemahaffeycheryld
 
Passive Air Cooling System and Solar Water Heater.ppt
Passive Air Cooling System and Solar Water Heater.pptPassive Air Cooling System and Solar Water Heater.ppt
Passive Air Cooling System and Solar Water Heater.pptamrabdallah9
 
8th International Conference on Soft Computing, Mathematics and Control (SMC ...
8th International Conference on Soft Computing, Mathematics and Control (SMC ...8th International Conference on Soft Computing, Mathematics and Control (SMC ...
8th International Conference on Soft Computing, Mathematics and Control (SMC ...josephjonse
 
Worksharing and 3D Modeling with Revit.pptx
Worksharing and 3D Modeling with Revit.pptxWorksharing and 3D Modeling with Revit.pptx
Worksharing and 3D Modeling with Revit.pptxMustafa Ahmed
 
What is Coordinate Measuring Machine? CMM Types, Features, Functions
What is Coordinate Measuring Machine? CMM Types, Features, FunctionsWhat is Coordinate Measuring Machine? CMM Types, Features, Functions
What is Coordinate Measuring Machine? CMM Types, Features, FunctionsVIEW
 
UNIT 4 PTRP final Convergence in probability.pptx
UNIT 4 PTRP final Convergence in probability.pptxUNIT 4 PTRP final Convergence in probability.pptx
UNIT 4 PTRP final Convergence in probability.pptxkalpana413121
 
Adsorption (mass transfer operations 2) ppt
Adsorption (mass transfer operations 2) pptAdsorption (mass transfer operations 2) ppt
Adsorption (mass transfer operations 2) pptjigup7320
 
CLOUD COMPUTING SERVICES - Cloud Reference Modal
CLOUD COMPUTING SERVICES - Cloud Reference ModalCLOUD COMPUTING SERVICES - Cloud Reference Modal
CLOUD COMPUTING SERVICES - Cloud Reference ModalSwarnaSLcse
 
Autodesk Construction Cloud (Autodesk Build).pptx
Autodesk Construction Cloud (Autodesk Build).pptxAutodesk Construction Cloud (Autodesk Build).pptx
Autodesk Construction Cloud (Autodesk Build).pptxMustafa Ahmed
 

Recently uploaded (20)

Diploma Engineering Drawing Qp-2024 Ece .pdf
Diploma Engineering Drawing Qp-2024 Ece .pdfDiploma Engineering Drawing Qp-2024 Ece .pdf
Diploma Engineering Drawing Qp-2024 Ece .pdf
 
Signal Processing and Linear System Analysis
Signal Processing and Linear System AnalysisSignal Processing and Linear System Analysis
Signal Processing and Linear System Analysis
 
Raashid final report on Embedded Systems
Raashid final report on Embedded SystemsRaashid final report on Embedded Systems
Raashid final report on Embedded Systems
 
DBMS-Report on Student management system.pptx
DBMS-Report on Student management system.pptxDBMS-Report on Student management system.pptx
DBMS-Report on Student management system.pptx
 
Basics of Relay for Engineering Students
Basics of Relay for Engineering StudentsBasics of Relay for Engineering Students
Basics of Relay for Engineering Students
 
Involute of a circle,Square, pentagon,HexagonInvolute_Engineering Drawing.pdf
Involute of a circle,Square, pentagon,HexagonInvolute_Engineering Drawing.pdfInvolute of a circle,Square, pentagon,HexagonInvolute_Engineering Drawing.pdf
Involute of a circle,Square, pentagon,HexagonInvolute_Engineering Drawing.pdf
 
Seismic Hazard Assessment Software in Python by Prof. Dr. Costas Sachpazis
Seismic Hazard Assessment Software in Python by Prof. Dr. Costas SachpazisSeismic Hazard Assessment Software in Python by Prof. Dr. Costas Sachpazis
Seismic Hazard Assessment Software in Python by Prof. Dr. Costas Sachpazis
 
History of Indian Railways - the story of Growth & Modernization
History of Indian Railways - the story of Growth & ModernizationHistory of Indian Railways - the story of Growth & Modernization
History of Indian Railways - the story of Growth & Modernization
 
Circuit Breakers for Engineering Students
Circuit Breakers for Engineering StudentsCircuit Breakers for Engineering Students
Circuit Breakers for Engineering Students
 
Working Principle of Echo Sounder and Doppler Effect.pdf
Working Principle of Echo Sounder and Doppler Effect.pdfWorking Principle of Echo Sounder and Doppler Effect.pdf
Working Principle of Echo Sounder and Doppler Effect.pdf
 
Theory of Time 2024 (Universal Theory for Everything)
Theory of Time 2024 (Universal Theory for Everything)Theory of Time 2024 (Universal Theory for Everything)
Theory of Time 2024 (Universal Theory for Everything)
 
Artificial Intelligence in due diligence
Artificial Intelligence in due diligenceArtificial Intelligence in due diligence
Artificial Intelligence in due diligence
 
Passive Air Cooling System and Solar Water Heater.ppt
Passive Air Cooling System and Solar Water Heater.pptPassive Air Cooling System and Solar Water Heater.ppt
Passive Air Cooling System and Solar Water Heater.ppt
 
8th International Conference on Soft Computing, Mathematics and Control (SMC ...
8th International Conference on Soft Computing, Mathematics and Control (SMC ...8th International Conference on Soft Computing, Mathematics and Control (SMC ...
8th International Conference on Soft Computing, Mathematics and Control (SMC ...
 
Worksharing and 3D Modeling with Revit.pptx
Worksharing and 3D Modeling with Revit.pptxWorksharing and 3D Modeling with Revit.pptx
Worksharing and 3D Modeling with Revit.pptx
 
What is Coordinate Measuring Machine? CMM Types, Features, Functions
What is Coordinate Measuring Machine? CMM Types, Features, FunctionsWhat is Coordinate Measuring Machine? CMM Types, Features, Functions
What is Coordinate Measuring Machine? CMM Types, Features, Functions
 
UNIT 4 PTRP final Convergence in probability.pptx
UNIT 4 PTRP final Convergence in probability.pptxUNIT 4 PTRP final Convergence in probability.pptx
UNIT 4 PTRP final Convergence in probability.pptx
 
Adsorption (mass transfer operations 2) ppt
Adsorption (mass transfer operations 2) pptAdsorption (mass transfer operations 2) ppt
Adsorption (mass transfer operations 2) ppt
 
CLOUD COMPUTING SERVICES - Cloud Reference Modal
CLOUD COMPUTING SERVICES - Cloud Reference ModalCLOUD COMPUTING SERVICES - Cloud Reference Modal
CLOUD COMPUTING SERVICES - Cloud Reference Modal
 
Autodesk Construction Cloud (Autodesk Build).pptx
Autodesk Construction Cloud (Autodesk Build).pptxAutodesk Construction Cloud (Autodesk Build).pptx
Autodesk Construction Cloud (Autodesk Build).pptx
 

Interface All The Things

  • 1. Interface All The Things 12 May 2015 Jonathan Gomez Engineer, Zumata
  • 2. Overview What are interfaces? Why they are awesome? Tips / Gotchas Illustrate via examples
  • 3. Intro to Interfaces typeGopherinterface{ Nod() Wink() } Could be read as, a Gopheris something that has these behaviours / actions: Ability to nod Ability to wink
  • 4. Intro to Interfaces Lets implement Nod()and Wink(): typeSingGopherstruct{} func(g*SingGopher)Nod(){ fmt.Println("cannod") } func(g*SingGopher)Wink(){ fmt.Println("winkalsocan") } By having these methods, SingGopherimplicitly satisfies the Gopherinterface. i.e. don't need to explicitly state that SingGopherimplements the interface.
  • 5. Intro to Interfaces With the interface satisfied, we can assign our SingGopherto the Gophertype. funcplay(gopherGopher){ gopher.Nod() gopher.Wink() } funcmain(){ play(&SingGopher{}) } Run
  • 6. Intro to Interfaces What if a method was missing? Think in terms of method sets: set of interface ⊆ set of concrete type funcmain(){ play(&SingGopher{}) } Run
  • 8. Why use interfaces? Abstract and avoid repetition e.g. Gopherprocessing code (business logic) funcpipeline(gophers...Gopher){ for_,gopher:=rangegophers{ play(gopher) } } As new gophers are added, no change is required. Note: Can define functions and methods that take interfaces, but can't define methods on the interface (e.g. gopher.Play()) funcmain(){ pipeline(&SingGopher{},&YodaGopher{}) } Run
  • 9. Why use interfaces? Combine simple units to achieve complexity Example of standard library's io.Readerinterface: typeReaderinterface{ Read(p[]byte)(nint,errerror) } Functions/methods that take io.Readerarguments are indifferent to where data is coming from. e.g. os.File, bytes.Buffer, net.Conn, http.Request.Body //json funcNewDecoder(rio.Reader)*Decoder //gzip funcNewReader(rio.Reader)(*Reader,error) Chain for complexity: response,_:=client.Do(request) raw,_:=gzip.NewReader(response.Body) json.NewDecoder(raw).Decode(&data)
  • 10. Why use interfaces? Sharing patterns Dropbox has a interesting caching library @ github.com/dropbox/godropbox (https://godoc.org/github.com/dropbox/godropbox/caching) Patterns of caching / managing storage funcNewCacheOnStorage(cache,storageStorage)Storage funcNewRateLimitedStorage(storageStorage,maxConcurrencyint)Storage Developers gain access via implementing Storageon their own: typeStorageinterface{ Get(...)(interface{},error) Set(...)error Delete(...)error ... } Tap into / contribute to the growing set of community resources
  • 11. Why use interfaces? Testing If our functions have interface args, we can test them with mock implementations i.e. use a FakeGopherto test our code that depends on Gopher typeFakeGopherstruct{ Noddedbool Winkedbool } func(g*FakeGopher)Nod(){ g.Nodded=true } func(g*FakeGopher)Wink(){ g.Winked=true } funcTestPlay(){ g:=&FakeGopher{} g.ShowState() play(g) g.ShowState() } Run
  • 12.
  • 13. Why use interfaces? Flexibility to change your lib/infra decisions In one of our apps, we use a 3rd party logging library, logrus. Avoid our codebase being coupled to it, by having an interface for logging. typeLoggerinterface{ Info(args...interface{}) Warn(args...interface{}) Error(args...interface{}) Infof(args...interface{}) Warnf(args...interface{}) Errorf(args...interface{}) } e.g. Publisherw/ Publish()(to queue) & Mailer& Mail()(3rd party service) Seize opportunities to decrease coupling / increase options. Better to do earlier than later.
  • 14. Why use interfaces? Flexibility for package consumers typeStorageinterface{ Get(...)(Kites,error) Add(...)error Update(...)error Delete(...)error Upsert(...)error } Interesting microservices project github.com/koding/kite(https://github.com/koding/kite) Storageinterface with Postgresand Etcdimplementations Useful here to give the consumer options Maybe unnecessary in your own app
  • 15. Why use interfaces? Very natural fit for some problems When standardisation is essential to design The method set creates the standard Project to create and manage Docker hosts across providers github.com/docker/machine(https://github.com/docker/machine) typeDriverinterface{ Create()error GetIP()(string,error) Start()error Stop()error ... } Implementations for Amazon, Google, Digital Ocean, Azure, OpenStack, Rackspace +
  • 16. Tips: Check out the standard library 100+ interfaces error Stringer Handler ResponseWriter sort.Interface Reader,Writer,ReadWriter, Marshaler,Umarshaler TB(tests,benchmarks) Convention is to name the one method interface Method-er Encouragement to keep interfaces small, but it isn't a hard rule Smaller = less work to satisfy Where your code can be compatible with standard library / community interfaces, will be more easily useable by others e.g. middleware that takes a Handlerand returns a Handler
  • 17. Tips: Use embedding to keep interfaces small Compose larger interfaces out of smaller ones typeReaderinterface{ Read(p[]byte)(nint,errerror) } typeWriterinterface{ Write(p[]byte)(nint,errerror) } typeReadWriterinterface{ Reader Writer } When method invoked, the receiver is the inner type, not outer Will reduce code complexity, encourage simpler implementations
  • 18. Tips: Type assert for accessing different functionality Assume some gophers are also coders which can Code() typeCoderinterface{ Code() } Runtime type assert to see whether the Gopheris a Coder& call Code() funcwriteCode(gopherGopher){ //ifourGophersatisfiesCoder,thentypeassert ifcoder,ok:=gopher.(Coder);ok{ coder.Code() } } Note: the coder can't call Nod()or Wink(). Considered an idiom in Go to convert type to access different methods.
  • 19. Tips: Interfaces and nil What is an interface? Implemented as a type and a value If type is set, and value is a nil pointer, the interface is not nil When implementing custom errors - return nil instead of interfaces with nil values. funcmain(){ varsingGopher*SingGopher vargopherGopher vargopher2Gopher=singGopher fmt.Println("values:") fmt.Println("singGopher:",singGopher,singGopher==nil) fmt.Println("gopher:",gopher,gopher==nil) fmt.Println("gopher2:",gopher2,gopher2==nil) fmt.Println("types:") fmt.Printf("singGopher:%#vn",singGopher) fmt.Printf("gopher:%#vn",gopher) fmt.Printf("gopher2:%#vn",gopher2) } Run
  • 21. Thank you Jonathan Gomez Engineer, Zumata jonathanbgomez@gmail.com(mailto:jonathanbgomez@gmail.com) @jonog(http://twitter.com/jonog)