SlideShare a Scribd company logo
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
Interface All The Things
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

PPTX
Interpreter Design Pattern in Javascript
Dmytro Verbovyi
 
PPT
Practical Meta Programming
Reggie Meisler
 
PPT
Advanced C programming
Claus Wu
 
PDF
Антихрупкий TypeScript | Odessa Frontend Meetup #17
OdessaFrontend
 
PDF
Swift, swiftly
Jack Nutting
 
PPT
Lập trình C
Viet NguyenHoang
 
PPT
Generic Programming seminar
Gautam Roy
 
PPTX
Presentation 5th
Connex
 
Interpreter Design Pattern in Javascript
Dmytro Verbovyi
 
Practical Meta Programming
Reggie Meisler
 
Advanced C programming
Claus Wu
 
Антихрупкий TypeScript | Odessa Frontend Meetup #17
OdessaFrontend
 
Swift, swiftly
Jack Nutting
 
Lập trình C
Viet NguyenHoang
 
Generic Programming seminar
Gautam Roy
 
Presentation 5th
Connex
 

What's hot (8)

PDF
Generic programming
Platonov Sergey
 
PPTX
Functional programming for production quality code
Jack Fox
 
PDF
Java 8 - Lambdas and much more
Alin Pandichi
 
PDF
46630497 fun-pointer-1
AmIt Prasad
 
PPTX
Python Programming Essentials - M6 - Code Blocks and Indentation
P3 InfoTech Solutions Pvt. Ltd.
 
PPTX
Python programming workshop session 1
Abdul Haseeb
 
PPTX
Python workshop session 6
Abdul Haseeb
 
PPT
C++ programming
viancagerone
 
Generic programming
Platonov Sergey
 
Functional programming for production quality code
Jack Fox
 
Java 8 - Lambdas and much more
Alin Pandichi
 
46630497 fun-pointer-1
AmIt Prasad
 
Python Programming Essentials - M6 - Code Blocks and Indentation
P3 InfoTech Solutions Pvt. Ltd.
 
Python programming workshop session 1
Abdul Haseeb
 
Python workshop session 6
Abdul Haseeb
 
C++ programming
viancagerone
 
Ad

Similar to Interface All The Things (20)

PDF
To GO or not to GO
superstas88
 
PPTX
The GO Language : From Beginners to Gophers
I.I.S. G. Vallauri - Fossano
 
PPT
Unit 7 Java
arnold 7490
 
PPTX
Building native Android applications with Mirah and Pindah
Nick Plante
 
PDF
Coding in GO - GDG SL - NSBM
Raveen Perera
 
PDF
Building End-to-End Apps Using Typescript
Gil Fink
 
PPT
Introduction to Go programming
Exotel
 
PDF
Introduction to Griffon
James Williams
 
PDF
The AWT and Swing
adil raja
 
PPT
Java: Java Applets
Tareq Hasan
 
PDF
What's new with JavaScript in GNOME: The 2020 edition (GUADEC 2020)
Igalia
 
PDF
Desarrollo para Android con Groovy
Software Guru
 
PDF
Geeks Anonymes - Le langage Go
Geeks Anonymes
 
PDF
Whoops! where did my architecture go?
Oliver Gierke
 
PPTX
Go. Why it goes
Sergey Pichkurov
 
PDF
Functional programming-advantages
Sergei Winitzki
 
PDF
Building End to-End Web Apps Using TypeScript
Gil Fink
 
PPT
Applets
poojapainter
 
PDF
Whoops! Where did my architecture go?
Oliver Gierke
 
PPT
Graphics programming in Java
Tushar B Kute
 
To GO or not to GO
superstas88
 
The GO Language : From Beginners to Gophers
I.I.S. G. Vallauri - Fossano
 
Unit 7 Java
arnold 7490
 
Building native Android applications with Mirah and Pindah
Nick Plante
 
Coding in GO - GDG SL - NSBM
Raveen Perera
 
Building End-to-End Apps Using Typescript
Gil Fink
 
Introduction to Go programming
Exotel
 
Introduction to Griffon
James Williams
 
The AWT and Swing
adil raja
 
Java: Java Applets
Tareq Hasan
 
What's new with JavaScript in GNOME: The 2020 edition (GUADEC 2020)
Igalia
 
Desarrollo para Android con Groovy
Software Guru
 
Geeks Anonymes - Le langage Go
Geeks Anonymes
 
Whoops! where did my architecture go?
Oliver Gierke
 
Go. Why it goes
Sergey Pichkurov
 
Functional programming-advantages
Sergei Winitzki
 
Building End to-End Web Apps Using TypeScript
Gil Fink
 
Applets
poojapainter
 
Whoops! Where did my architecture go?
Oliver Gierke
 
Graphics programming in Java
Tushar B Kute
 
Ad

Recently uploaded (20)

PPTX
business incubation centre aaaaaaaaaaaaaa
hodeeesite4
 
PDF
Chad Ayach - A Versatile Aerospace Professional
Chad Ayach
 
PDF
LEAP-1B presedntation xxxxxxxxxxxxxxxxxxxxxxxxxxxxx
hatem173148
 
PDF
Zero Carbon Building Performance standard
BassemOsman1
 
PDF
Packaging Tips for Stainless Steel Tubes and Pipes
heavymetalsandtubes
 
PPTX
Tunnel Ventilation System in Kanpur Metro
220105053
 
PDF
Biodegradable Plastics: Innovations and Market Potential (www.kiu.ac.ug)
publication11
 
PDF
67243-Cooling and Heating & Calculation.pdf
DHAKA POLYTECHNIC
 
PPTX
Chapter_Seven_Construction_Reliability_Elective_III_Msc CM
SubashKumarBhattarai
 
PDF
Unit I Part II.pdf : Security Fundamentals
Dr. Madhuri Jawale
 
PDF
Introduction to Ship Engine Room Systems.pdf
Mahmoud Moghtaderi
 
PDF
Natural_Language_processing_Unit_I_notes.pdf
sanguleumeshit
 
PPTX
Victory Precisions_Supplier Profile.pptx
victoryprecisions199
 
PDF
67243-Cooling and Heating & Calculation.pdf
DHAKA POLYTECHNIC
 
PDF
Construction of a Thermal Vacuum Chamber for Environment Test of Triple CubeS...
2208441
 
PPT
Understanding the Key Components and Parts of a Drone System.ppt
Siva Reddy
 
PDF
20ME702-Mechatronics-UNIT-1,UNIT-2,UNIT-3,UNIT-4,UNIT-5, 2025-2026
Mohanumar S
 
PDF
All chapters of Strength of materials.ppt
girmabiniyam1234
 
PPTX
IoT_Smart_Agriculture_Presentations.pptx
poojakumari696707
 
PDF
FLEX-LNG-Company-Presentation-Nov-2017.pdf
jbloggzs
 
business incubation centre aaaaaaaaaaaaaa
hodeeesite4
 
Chad Ayach - A Versatile Aerospace Professional
Chad Ayach
 
LEAP-1B presedntation xxxxxxxxxxxxxxxxxxxxxxxxxxxxx
hatem173148
 
Zero Carbon Building Performance standard
BassemOsman1
 
Packaging Tips for Stainless Steel Tubes and Pipes
heavymetalsandtubes
 
Tunnel Ventilation System in Kanpur Metro
220105053
 
Biodegradable Plastics: Innovations and Market Potential (www.kiu.ac.ug)
publication11
 
67243-Cooling and Heating & Calculation.pdf
DHAKA POLYTECHNIC
 
Chapter_Seven_Construction_Reliability_Elective_III_Msc CM
SubashKumarBhattarai
 
Unit I Part II.pdf : Security Fundamentals
Dr. Madhuri Jawale
 
Introduction to Ship Engine Room Systems.pdf
Mahmoud Moghtaderi
 
Natural_Language_processing_Unit_I_notes.pdf
sanguleumeshit
 
Victory Precisions_Supplier Profile.pptx
victoryprecisions199
 
67243-Cooling and Heating & Calculation.pdf
DHAKA POLYTECHNIC
 
Construction of a Thermal Vacuum Chamber for Environment Test of Triple CubeS...
2208441
 
Understanding the Key Components and Parts of a Drone System.ppt
Siva Reddy
 
20ME702-Mechatronics-UNIT-1,UNIT-2,UNIT-3,UNIT-4,UNIT-5, 2025-2026
Mohanumar S
 
All chapters of Strength of materials.ppt
girmabiniyam1234
 
IoT_Smart_Agriculture_Presentations.pptx
poojakumari696707
 
FLEX-LNG-Company-Presentation-Nov-2017.pdf
jbloggzs
 

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
  • 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 [email protected](mailto:[email protected]) @jonog(http://twitter.com/jonog)