SlideShare ist ein Scribd-Unternehmen logo
1 von 56
Downloaden Sie, um offline zu lesen
Go for Object 

Oriented Programmers
!
or
!
Object Oriented Programming 

Without Objects
• Author of Hugo, Cobra,
Viper & More
• Chief Developer
Advocate for MongoDB
• Gopher
@spf13
— txxxxd
“Most of the appeal for me is not
the features that Go has, but
rather the features that have
been intentionally left out.”
— Rob Pike
“Why would you have a
language that is not
theoretically exciting?
Because it’s very useful.”
“Objects” 

in Go
Does Go have Objects?
• Go lacks Classes
• Go lacks “Objects”
What is an
Object?
– Steve Francia
“An object is an
abstract data type that
has state (data) and
behavior (code).”
type Rect struct {
width int
height int
}
Type Declaration (Struct)
func (r *Rect) Area() int {
return r.width * r.height
}
Declaring a Method
func main() {
r := Rect{width: 10, height: 5}
fmt.Println("area: ", r.Area())
}
In Action
type Rects []Rect
Type Declaration (Slice)
func (rs Rects) Area() int {
var a int
for _, r := range rs {
a += r.Area()
}
return a
}
Declaring a Method
func main() {
r := Rect{width: 10, height: 5}
x := Rect{width: 7, height:10}
rs := Rects{r, x}
fmt.Println("r's area: ", r.Area())
fmt.Println("x's area: ", x.Area())
fmt.Println("total area: ", rs.Area())
}
In Action
http://play.golang.org/p/G1OWXPGvc3
type Foo func() int
Type Declaration (Func)
func (f Foo) Add(x int) int {
return f() + x
}
Declaring a Method
func main() {
var x Foo
!
x = func() int { return 1 }
!
fmt.Println(x())
fmt.Println(x.Add(3))
}
In Action
http://play.golang.org/p/YGrdCG3SlI
Go Has
“Objects”
“Object Oriented”
Go
– Wikipedia
A language is usually considered object-based
if it includes the basic capabilities for an
object: identity, properties, and attributes.


A language is considered object-oriented if it
is object-based and also has the capability of
polymorphism and inheritance.
Go is Object Based.
!
Is it OO?
Inheritance
• Provides reuse of objects
• Classes are created in hierarchies
• Inheritance lets the structure and
methods in one class pass down the
hierarchy
Go’s approach
• Go explicitly avoided inheritance
• Go strictly follows the composition over
inheritance principle
• Composition through embedded types
Composition
• Provides reuse of Objects
• One object is declared by including other
objects
• Composition lets the structure and methods
in one class be pulled into another
– Steve Francia
Inheritance passes “knowledge” down
!
Composition pulls “knowledge” up
type Person struct {
Name string
Address
}
!
!
type Address struct {
Number string
Street string
City string
State string
Zip string
}
Embedding Types
Inner Type
func (a *Address) String() string {
return a.Number+" "+a.Street+"n"+

a.City+", "+a.State+" "+a.Zip+"n"
}
Declaring a Method
func main() {
p := Person{
Name: "Steve",
Address: Address{
Number: "13",
Street: "Main",
City: "Gotham",
State: "NY",
Zip: "01313",
},
}
}
Declare using Composite Literal
func main() {
p := Person{
Name: "Steve",
Address: Address{
Number: "13",
Street: "Main",
City: "Gotham",
State: "NY",
Zip: "01313",
},
}
fmt.Println(p.String())
In Action
http://play.golang.org/p/9beVY9jNlW
Promotion
• Promotion looks to see if a single inner type can
satisify the request and “promotes” it
• Embedded fields & methods are “promoted”
• Promotion only occurs during usage, not declaration
• Promoted methods are considered for interface
adherance
func (a *Address) String() string {
return a.Number+" "+a.Street+"n"+

a.City+", "+a.State+" "+a.Zip+"n"
}
!
func (p *Person) String() string {
return p.Name + "n" + p.Address.String()
}
Not Overloading
func main() {
p := Person{
Name: "Steve",
Address: Address{
Number: "13",
Street: "Main",
City: "Gotham",
State: "NY",
Zip: "01313",
},
}
!
fmt.Println(p.String())
fmt.Println(p.Address.String())
}
Both Methods Available
http://play.golang.org/p/Aui0nGa5Xi
func isValidAddress(a *Address) bool {
return a.Street != ""
}
!
func main() {
p := Person{ Name: "Steve", Address: Address{ Number: "13", Street:
"Main", City: "Gotham", State: "NY", Zip: "01313"}}
!
fmt.Println(isValidAddress(p)) 

// cannot use p (type Person) as type Address 

// in argument to isValidAddress
fmt.Println(isValidAddress(p.Address))
}
Types Remain Distinct
http://play.golang.org/p/KYjXZxNBcQ
Promotion is
NOT Subtyping
Polymorphism
• “The provision of a single interface to
entities of different types”
• Typically implmented via Generics,
Overloading and/or Subtyping
Go’s approach
• Go explicitly avoided subtyping &
overloading
• Go does not provide Generics (yet)
• Go’s interface provide polymorphic
capabilities
Interfaces
• A list of required methods
• Structural vs Nominal typing
• ‘‘If something can do this, then it can be
used here”
• Convention is call it a Something-er
type Shaper interface {
Area() int
}
Interface Declaration
func Describe(s Shaper) {
fmt.Println("Area is:", s.Area())
}
Using Interface as Param Type
func main() {
r := &Rect{width: 10, height: 5}
x := &Rect{width: 7, height: 10}
rs := &Rects{r, x}
Describe(r)
Describe(x)
Describe(rs)
}
In Action
http://play.golang.org/p/WL77LihUwi
–James Gosling (creator of Java)
“If you could do Java over again, what would you
change?” “I’d leave out classes,” he replied. After the
laughter died down, he explained that the real
problem wasn’t classes per se, but rather
implementation inheritance (the extends
relationship). Interface inheritance (the implements
relationship) is preferable. You should avoid
implementation inheritance whenever possible.
Go Interfaces are
based on
implementation,
not declaration
The Power of
Interfaces
type Reader interface {
Read(p []byte) (n int, err error)
}
io.Reader
io.Reader
• Interface
• Read reads up to len(p) bytes into p
• Returns the # of bytes read & any error
• Does not dictate how Read() is implemented
• Used by os.File, bytes.Buffer, net.Conn,
http.Request.Body, loads more
type Writer interface {
Write(p []byte) (n int, err error)
}
io.Writer
io.Writer
• Interface
• Write writes up to len(p) bytes into p
• Returns the # of bytes written & any error
• Does not dictate how Write() is implemented
• Used by os.File, bytes.Buffer, net.Conn,
http.Response.Body, loads more
func MarshalGzippedJSON(r io.Reader, 

v interface{}) error {
raw, err := gzip.NewReader(r)
if err != nil {
return err
}
return json.NewDecoder(raw).Decode(&v)
}
io.Reader in Action
f, err := os.Open("myfile.json.gz")
if err != nil {
log.Fatalln(err)
}
defer f.Close()
m = make(map[string]interface{})
MarshalGzippedJSON(f, &m)
Reading a json.gz file
Practical Interoperability
• Gzip.NewReader(io.Reader)
• Works on files, http requests, byte buffers,
network connections, …anything you create
• Nothing special needed in gzip to be able to
do this… Simply call Read(n) and leave the
abstracting to the implementor
func main() {
resp, err := http.Get("...")
if err != nil {
log.Fatalln(err)
}
defer resp.Body.Close()
out, err := os.Create("filename.ext")
if err != nil {
log.Fatalln(err)
}
defer out.Close()
io.Copy(out, resp.Body) // out io.Writer, resp.Body io.Reader
}
Pipe http response to file
Go
— Steve Jobs
Simple can be harder than
complex: You have to work hard
to get your thinking clean to
make it simple. But it's worth it
in the end because once you get
there, you can move mountains.
Go is simple,
pratical &
wonderful
Go build
something
great
Thank You

Weitere ähnliche Inhalte

Was ist angesagt?

Happy Go Programming
Happy Go ProgrammingHappy Go Programming
Happy Go ProgrammingLin Yo-An
 
Vim Script Programming
Vim Script ProgrammingVim Script Programming
Vim Script ProgrammingLin Yo-An
 
EuroPython 2016 - Do I Need To Switch To Golang
EuroPython 2016 - Do I Need To Switch To GolangEuroPython 2016 - Do I Need To Switch To Golang
EuroPython 2016 - Do I Need To Switch To GolangMax Tepkeev
 
Learning go for perl programmers
Learning go for perl programmersLearning go for perl programmers
Learning go for perl programmersFred Moyer
 
Python internals and how they affect your code - kasra ahmadvand
Python internals and how they affect your code - kasra ahmadvandPython internals and how they affect your code - kasra ahmadvand
Python internals and how they affect your code - kasra ahmadvandirpycon
 
Golang iran - tutorial go programming language - Preliminary
Golang iran - tutorial  go programming language - PreliminaryGolang iran - tutorial  go programming language - Preliminary
Golang iran - tutorial go programming language - Preliminarygo-lang
 
Go for Rubyists
Go for RubyistsGo for Rubyists
Go for Rubyiststchandy
 
Monitoring and Debugging your Live Applications
Monitoring and Debugging your Live ApplicationsMonitoring and Debugging your Live Applications
Monitoring and Debugging your Live ApplicationsRobert Coup
 
Learning Python from Data
Learning Python from DataLearning Python from Data
Learning Python from DataMosky Liu
 
PyCon 2013 : Scripting to PyPi to GitHub and More
PyCon 2013 : Scripting to PyPi to GitHub and MorePyCon 2013 : Scripting to PyPi to GitHub and More
PyCon 2013 : Scripting to PyPi to GitHub and MoreMatt Harrison
 
How to build SDKs in Go
How to build SDKs in GoHow to build SDKs in Go
How to build SDKs in GoDiwaker Gupta
 
Why Python (for Statisticians)
Why Python (for Statisticians)Why Python (for Statisticians)
Why Python (for Statisticians)Matt Harrison
 
Introduction to Google's Go programming language
Introduction to Google's Go programming languageIntroduction to Google's Go programming language
Introduction to Google's Go programming languageMario Castro Contreras
 
Beauty and Power of Go
Beauty and Power of GoBeauty and Power of Go
Beauty and Power of GoFrank Müller
 
XPath for web scraping
XPath for web scrapingXPath for web scraping
XPath for web scrapingScrapinghub
 
Python: an introduction for PHP webdevelopers
Python: an introduction for PHP webdevelopersPython: an introduction for PHP webdevelopers
Python: an introduction for PHP webdevelopersGlenn De Backer
 

Was ist angesagt? (20)

Happy Go Programming
Happy Go ProgrammingHappy Go Programming
Happy Go Programming
 
Vim Script Programming
Vim Script ProgrammingVim Script Programming
Vim Script Programming
 
EuroPython 2016 - Do I Need To Switch To Golang
EuroPython 2016 - Do I Need To Switch To GolangEuroPython 2016 - Do I Need To Switch To Golang
EuroPython 2016 - Do I Need To Switch To Golang
 
Learning go for perl programmers
Learning go for perl programmersLearning go for perl programmers
Learning go for perl programmers
 
Go Lang Tutorial
Go Lang TutorialGo Lang Tutorial
Go Lang Tutorial
 
Python internals and how they affect your code - kasra ahmadvand
Python internals and how they affect your code - kasra ahmadvandPython internals and how they affect your code - kasra ahmadvand
Python internals and how they affect your code - kasra ahmadvand
 
Golang iran - tutorial go programming language - Preliminary
Golang iran - tutorial  go programming language - PreliminaryGolang iran - tutorial  go programming language - Preliminary
Golang iran - tutorial go programming language - Preliminary
 
Golang
GolangGolang
Golang
 
Go for Rubyists
Go for RubyistsGo for Rubyists
Go for Rubyists
 
Monitoring and Debugging your Live Applications
Monitoring and Debugging your Live ApplicationsMonitoring and Debugging your Live Applications
Monitoring and Debugging your Live Applications
 
Hacking with hhvm
Hacking with hhvmHacking with hhvm
Hacking with hhvm
 
IO Streams, Files and Directories
IO Streams, Files and DirectoriesIO Streams, Files and Directories
IO Streams, Files and Directories
 
Learning Python from Data
Learning Python from DataLearning Python from Data
Learning Python from Data
 
PyCon 2013 : Scripting to PyPi to GitHub and More
PyCon 2013 : Scripting to PyPi to GitHub and MorePyCon 2013 : Scripting to PyPi to GitHub and More
PyCon 2013 : Scripting to PyPi to GitHub and More
 
How to build SDKs in Go
How to build SDKs in GoHow to build SDKs in Go
How to build SDKs in Go
 
Why Python (for Statisticians)
Why Python (for Statisticians)Why Python (for Statisticians)
Why Python (for Statisticians)
 
Introduction to Google's Go programming language
Introduction to Google's Go programming languageIntroduction to Google's Go programming language
Introduction to Google's Go programming language
 
Beauty and Power of Go
Beauty and Power of GoBeauty and Power of Go
Beauty and Power of Go
 
XPath for web scraping
XPath for web scrapingXPath for web scraping
XPath for web scraping
 
Python: an introduction for PHP webdevelopers
Python: an introduction for PHP webdevelopersPython: an introduction for PHP webdevelopers
Python: an introduction for PHP webdevelopers
 

Andere mochten auch

The Future of the Operating System - Keynote LinuxCon 2015
The Future of the Operating System -  Keynote LinuxCon 2015The Future of the Operating System -  Keynote LinuxCon 2015
The Future of the Operating System - Keynote LinuxCon 2015Steven Francia
 
What every successful open source project needs
What every successful open source project needsWhat every successful open source project needs
What every successful open source project needsSteven Francia
 
Build your first MongoDB App in Ruby @ StrangeLoop 2013
Build your first MongoDB App in Ruby @ StrangeLoop 2013Build your first MongoDB App in Ruby @ StrangeLoop 2013
Build your first MongoDB App in Ruby @ StrangeLoop 2013Steven Francia
 
Big data for the rest of us
Big data for the rest of usBig data for the rest of us
Big data for the rest of usSteven Francia
 
MongoDB, Hadoop and humongous data - MongoSV 2012
MongoDB, Hadoop and humongous data - MongoSV 2012MongoDB, Hadoop and humongous data - MongoSV 2012
MongoDB, Hadoop and humongous data - MongoSV 2012Steven Francia
 
OSCON 2012 MongoDB Tutorial
OSCON 2012 MongoDB TutorialOSCON 2012 MongoDB Tutorial
OSCON 2012 MongoDB TutorialSteven Francia
 
20. Object-Oriented Programming Fundamental Principles
20. Object-Oriented Programming Fundamental Principles20. Object-Oriented Programming Fundamental Principles
20. Object-Oriented Programming Fundamental PrinciplesIntro C# Book
 
Object-oriented programming
Object-oriented programmingObject-oriented programming
Object-oriented programmingNeelesh Shukla
 
Demystifying Object-Oriented Programming - PHP UK Conference 2017
Demystifying Object-Oriented Programming - PHP UK Conference 2017Demystifying Object-Oriented Programming - PHP UK Conference 2017
Demystifying Object-Oriented Programming - PHP UK Conference 2017Alena Holligan
 
Mongo db - How we use Go and MongoDB by Sam Helman
Mongo db - How we use Go and MongoDB by Sam HelmanMongo db - How we use Go and MongoDB by Sam Helman
Mongo db - How we use Go and MongoDB by Sam HelmanHakka Labs
 
Concepts In Object Oriented Programming Languages
Concepts In Object Oriented Programming LanguagesConcepts In Object Oriented Programming Languages
Concepts In Object Oriented Programming Languagesppd1961
 
Object Oriented Concept
Object Oriented ConceptObject Oriented Concept
Object Oriented Conceptsmj
 
Need of object oriented programming
Need of object oriented programmingNeed of object oriented programming
Need of object oriented programmingAmar Jukuntla
 
Architecting for the Cloud using NetflixOSS - Codemash Workshop
Architecting for the Cloud using NetflixOSS - Codemash WorkshopArchitecting for the Cloud using NetflixOSS - Codemash Workshop
Architecting for the Cloud using NetflixOSS - Codemash WorkshopSudhir Tonse
 
oops concept in java | object oriented programming in java
oops concept in java | object oriented programming in javaoops concept in java | object oriented programming in java
oops concept in java | object oriented programming in javaCPD INDIA
 
Object oriented programming (oop) cs304 power point slides lecture 01
Object oriented programming (oop)   cs304 power point slides lecture 01Object oriented programming (oop)   cs304 power point slides lecture 01
Object oriented programming (oop) cs304 power point slides lecture 01Adil Kakakhel
 
Basic concepts of object oriented programming
Basic concepts of object oriented programmingBasic concepts of object oriented programming
Basic concepts of object oriented programmingSachin Sharma
 
Introduction to Object Oriented Programming
Introduction to Object Oriented ProgrammingIntroduction to Object Oriented Programming
Introduction to Object Oriented ProgrammingMoutaz Haddara
 

Andere mochten auch (20)

The Future of the Operating System - Keynote LinuxCon 2015
The Future of the Operating System -  Keynote LinuxCon 2015The Future of the Operating System -  Keynote LinuxCon 2015
The Future of the Operating System - Keynote LinuxCon 2015
 
What every successful open source project needs
What every successful open source project needsWhat every successful open source project needs
What every successful open source project needs
 
Build your first MongoDB App in Ruby @ StrangeLoop 2013
Build your first MongoDB App in Ruby @ StrangeLoop 2013Build your first MongoDB App in Ruby @ StrangeLoop 2013
Build your first MongoDB App in Ruby @ StrangeLoop 2013
 
Big data for the rest of us
Big data for the rest of usBig data for the rest of us
Big data for the rest of us
 
MongoDB, Hadoop and humongous data - MongoSV 2012
MongoDB, Hadoop and humongous data - MongoSV 2012MongoDB, Hadoop and humongous data - MongoSV 2012
MongoDB, Hadoop and humongous data - MongoSV 2012
 
OSCON 2012 MongoDB Tutorial
OSCON 2012 MongoDB TutorialOSCON 2012 MongoDB Tutorial
OSCON 2012 MongoDB Tutorial
 
20. Object-Oriented Programming Fundamental Principles
20. Object-Oriented Programming Fundamental Principles20. Object-Oriented Programming Fundamental Principles
20. Object-Oriented Programming Fundamental Principles
 
Object-oriented programming
Object-oriented programmingObject-oriented programming
Object-oriented programming
 
Demystifying Object-Oriented Programming - PHP UK Conference 2017
Demystifying Object-Oriented Programming - PHP UK Conference 2017Demystifying Object-Oriented Programming - PHP UK Conference 2017
Demystifying Object-Oriented Programming - PHP UK Conference 2017
 
Mongo db - How we use Go and MongoDB by Sam Helman
Mongo db - How we use Go and MongoDB by Sam HelmanMongo db - How we use Go and MongoDB by Sam Helman
Mongo db - How we use Go and MongoDB by Sam Helman
 
Concepts In Object Oriented Programming Languages
Concepts In Object Oriented Programming LanguagesConcepts In Object Oriented Programming Languages
Concepts In Object Oriented Programming Languages
 
Object Oriented Concept
Object Oriented ConceptObject Oriented Concept
Object Oriented Concept
 
Need of object oriented programming
Need of object oriented programmingNeed of object oriented programming
Need of object oriented programming
 
Architecting for the Cloud using NetflixOSS - Codemash Workshop
Architecting for the Cloud using NetflixOSS - Codemash WorkshopArchitecting for the Cloud using NetflixOSS - Codemash Workshop
Architecting for the Cloud using NetflixOSS - Codemash Workshop
 
oops concept in java | object oriented programming in java
oops concept in java | object oriented programming in javaoops concept in java | object oriented programming in java
oops concept in java | object oriented programming in java
 
Object oriented programming (oop) cs304 power point slides lecture 01
Object oriented programming (oop)   cs304 power point slides lecture 01Object oriented programming (oop)   cs304 power point slides lecture 01
Object oriented programming (oop) cs304 power point slides lecture 01
 
Basic concepts of object oriented programming
Basic concepts of object oriented programmingBasic concepts of object oriented programming
Basic concepts of object oriented programming
 
Object-oriented concepts
Object-oriented conceptsObject-oriented concepts
Object-oriented concepts
 
Introduction to Object Oriented Programming
Introduction to Object Oriented ProgrammingIntroduction to Object Oriented Programming
Introduction to Object Oriented Programming
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to java
 

Ähnlich wie Go for Object Oriented Programmers or Object Oriented Programming without Objects

sbt, history of JSON libraries, microservices, and schema evolution (Tokyo ver)
sbt, history of JSON libraries, microservices, and schema evolution (Tokyo ver)sbt, history of JSON libraries, microservices, and schema evolution (Tokyo ver)
sbt, history of JSON libraries, microservices, and schema evolution (Tokyo ver)Eugene Yokota
 
C# 6 and 7 and Futures 20180607
C# 6 and 7 and Futures 20180607C# 6 and 7 and Futures 20180607
C# 6 and 7 and Futures 20180607Kevin Hazzard
 
Tuga IT 2017 - What's new in C# 7
Tuga IT 2017 - What's new in C# 7Tuga IT 2017 - What's new in C# 7
Tuga IT 2017 - What's new in C# 7Paulo Morgado
 
Kotlin Austin Droids April 14 2016
Kotlin Austin Droids April 14 2016Kotlin Austin Droids April 14 2016
Kotlin Austin Droids April 14 2016DesertJames
 
Denis Lebedev, Swift
Denis  Lebedev, SwiftDenis  Lebedev, Swift
Denis Lebedev, SwiftYandex
 
EmberConf 2021 - Crossfile Codemodding with Joshua Lawrence
EmberConf 2021 - Crossfile Codemodding with Joshua LawrenceEmberConf 2021 - Crossfile Codemodding with Joshua Lawrence
EmberConf 2021 - Crossfile Codemodding with Joshua LawrenceJoshua Lawrence
 
Extreme Swift
Extreme SwiftExtreme Swift
Extreme SwiftMovel
 
Scala the language matters
Scala the language mattersScala the language matters
Scala the language mattersXiaojun REN
 
ITT 2015 - Saul Mora - Object Oriented Function Programming
ITT 2015 - Saul Mora - Object Oriented Function ProgrammingITT 2015 - Saul Mora - Object Oriented Function Programming
ITT 2015 - Saul Mora - Object Oriented Function ProgrammingIstanbul Tech Talks
 
型ヒントについて考えよう!
型ヒントについて考えよう!型ヒントについて考えよう!
型ヒントについて考えよう!Yusuke Miyazaki
 
2007 09 10 Fzi Training Groovy Grails V Ws
2007 09 10 Fzi Training Groovy Grails V Ws2007 09 10 Fzi Training Groovy Grails V Ws
2007 09 10 Fzi Training Groovy Grails V Wsloffenauer
 
The Kotlin Programming Language
The Kotlin Programming LanguageThe Kotlin Programming Language
The Kotlin Programming Languageintelliyole
 
devLink - What's New in C# 4?
devLink - What's New in C# 4?devLink - What's New in C# 4?
devLink - What's New in C# 4?Kevin Pilch
 

Ähnlich wie Go for Object Oriented Programmers or Object Oriented Programming without Objects (20)

Introduction to Go
Introduction to GoIntroduction to Go
Introduction to Go
 
sbt, history of JSON libraries, microservices, and schema evolution (Tokyo ver)
sbt, history of JSON libraries, microservices, and schema evolution (Tokyo ver)sbt, history of JSON libraries, microservices, and schema evolution (Tokyo ver)
sbt, history of JSON libraries, microservices, and schema evolution (Tokyo ver)
 
Json the-x-in-ajax1588
Json the-x-in-ajax1588Json the-x-in-ajax1588
Json the-x-in-ajax1588
 
Go Workshop Day 1
Go Workshop Day 1Go Workshop Day 1
Go Workshop Day 1
 
C# 6 and 7 and Futures 20180607
C# 6 and 7 and Futures 20180607C# 6 and 7 and Futures 20180607
C# 6 and 7 and Futures 20180607
 
Tuga IT 2017 - What's new in C# 7
Tuga IT 2017 - What's new in C# 7Tuga IT 2017 - What's new in C# 7
Tuga IT 2017 - What's new in C# 7
 
Kotlin Austin Droids April 14 2016
Kotlin Austin Droids April 14 2016Kotlin Austin Droids April 14 2016
Kotlin Austin Droids April 14 2016
 
Javascript
JavascriptJavascript
Javascript
 
Denis Lebedev, Swift
Denis  Lebedev, SwiftDenis  Lebedev, Swift
Denis Lebedev, Swift
 
EmberConf 2021 - Crossfile Codemodding with Joshua Lawrence
EmberConf 2021 - Crossfile Codemodding with Joshua LawrenceEmberConf 2021 - Crossfile Codemodding with Joshua Lawrence
EmberConf 2021 - Crossfile Codemodding with Joshua Lawrence
 
Extreme Swift
Extreme SwiftExtreme Swift
Extreme Swift
 
Scala the language matters
Scala the language mattersScala the language matters
Scala the language matters
 
ITT 2015 - Saul Mora - Object Oriented Function Programming
ITT 2015 - Saul Mora - Object Oriented Function ProgrammingITT 2015 - Saul Mora - Object Oriented Function Programming
ITT 2015 - Saul Mora - Object Oriented Function Programming
 
Go react codelab
Go react codelabGo react codelab
Go react codelab
 
Dynamic Python
Dynamic PythonDynamic Python
Dynamic Python
 
Json at work overview and ecosystem-v2.0
Json at work   overview and ecosystem-v2.0Json at work   overview and ecosystem-v2.0
Json at work overview and ecosystem-v2.0
 
型ヒントについて考えよう!
型ヒントについて考えよう!型ヒントについて考えよう!
型ヒントについて考えよう!
 
2007 09 10 Fzi Training Groovy Grails V Ws
2007 09 10 Fzi Training Groovy Grails V Ws2007 09 10 Fzi Training Groovy Grails V Ws
2007 09 10 Fzi Training Groovy Grails V Ws
 
The Kotlin Programming Language
The Kotlin Programming LanguageThe Kotlin Programming Language
The Kotlin Programming Language
 
devLink - What's New in C# 4?
devLink - What's New in C# 4?devLink - What's New in C# 4?
devLink - What's New in C# 4?
 

Mehr von Steven Francia

State of the Gopher Nation - Golang - August 2017
State of the Gopher Nation - Golang - August 2017State of the Gopher Nation - Golang - August 2017
State of the Gopher Nation - Golang - August 2017Steven Francia
 
Modern Database Systems (for Genealogy)
Modern Database Systems (for Genealogy)Modern Database Systems (for Genealogy)
Modern Database Systems (for Genealogy)Steven Francia
 
Introduction to MongoDB and Hadoop
Introduction to MongoDB and HadoopIntroduction to MongoDB and Hadoop
Introduction to MongoDB and HadoopSteven Francia
 
Replication, Durability, and Disaster Recovery
Replication, Durability, and Disaster RecoveryReplication, Durability, and Disaster Recovery
Replication, Durability, and Disaster RecoverySteven Francia
 
Multi Data Center Strategies
Multi Data Center StrategiesMulti Data Center Strategies
Multi Data Center StrategiesSteven Francia
 
NoSQL databases and managing big data
NoSQL databases and managing big dataNoSQL databases and managing big data
NoSQL databases and managing big dataSteven Francia
 
MongoDB, Hadoop and Humongous Data
MongoDB, Hadoop and Humongous DataMongoDB, Hadoop and Humongous Data
MongoDB, Hadoop and Humongous DataSteven Francia
 
Hybrid MongoDB and RDBMS Applications
Hybrid MongoDB and RDBMS ApplicationsHybrid MongoDB and RDBMS Applications
Hybrid MongoDB and RDBMS ApplicationsSteven Francia
 
Building your first application w/mongoDB MongoSV2011
Building your first application w/mongoDB MongoSV2011Building your first application w/mongoDB MongoSV2011
Building your first application w/mongoDB MongoSV2011Steven Francia
 
MongoDB, E-commerce and Transactions
MongoDB, E-commerce and TransactionsMongoDB, E-commerce and Transactions
MongoDB, E-commerce and TransactionsSteven Francia
 
MongoDB, PHP and the cloud - php cloud summit 2011
MongoDB, PHP and the cloud - php cloud summit 2011MongoDB, PHP and the cloud - php cloud summit 2011
MongoDB, PHP and the cloud - php cloud summit 2011Steven Francia
 
MongoDB and PHP ZendCon 2011
MongoDB and PHP ZendCon 2011MongoDB and PHP ZendCon 2011
MongoDB and PHP ZendCon 2011Steven Francia
 
Blending MongoDB and RDBMS for ecommerce
Blending MongoDB and RDBMS for ecommerceBlending MongoDB and RDBMS for ecommerce
Blending MongoDB and RDBMS for ecommerceSteven Francia
 
Augmenting RDBMS with MongoDB for ecommerce
Augmenting RDBMS with MongoDB for ecommerceAugmenting RDBMS with MongoDB for ecommerce
Augmenting RDBMS with MongoDB for ecommerceSteven Francia
 
MongoDB and Ecommerce : A perfect combination
MongoDB and Ecommerce : A perfect combinationMongoDB and Ecommerce : A perfect combination
MongoDB and Ecommerce : A perfect combinationSteven Francia
 

Mehr von Steven Francia (19)

State of the Gopher Nation - Golang - August 2017
State of the Gopher Nation - Golang - August 2017State of the Gopher Nation - Golang - August 2017
State of the Gopher Nation - Golang - August 2017
 
Modern Database Systems (for Genealogy)
Modern Database Systems (for Genealogy)Modern Database Systems (for Genealogy)
Modern Database Systems (for Genealogy)
 
Introduction to MongoDB and Hadoop
Introduction to MongoDB and HadoopIntroduction to MongoDB and Hadoop
Introduction to MongoDB and Hadoop
 
Future of data
Future of dataFuture of data
Future of data
 
Replication, Durability, and Disaster Recovery
Replication, Durability, and Disaster RecoveryReplication, Durability, and Disaster Recovery
Replication, Durability, and Disaster Recovery
 
Multi Data Center Strategies
Multi Data Center StrategiesMulti Data Center Strategies
Multi Data Center Strategies
 
NoSQL databases and managing big data
NoSQL databases and managing big dataNoSQL databases and managing big data
NoSQL databases and managing big data
 
MongoDB, Hadoop and Humongous Data
MongoDB, Hadoop and Humongous DataMongoDB, Hadoop and Humongous Data
MongoDB, Hadoop and Humongous Data
 
MongoDB and hadoop
MongoDB and hadoopMongoDB and hadoop
MongoDB and hadoop
 
MongoDB for Genealogy
MongoDB for GenealogyMongoDB for Genealogy
MongoDB for Genealogy
 
Hybrid MongoDB and RDBMS Applications
Hybrid MongoDB and RDBMS ApplicationsHybrid MongoDB and RDBMS Applications
Hybrid MongoDB and RDBMS Applications
 
Building your first application w/mongoDB MongoSV2011
Building your first application w/mongoDB MongoSV2011Building your first application w/mongoDB MongoSV2011
Building your first application w/mongoDB MongoSV2011
 
MongoDB, E-commerce and Transactions
MongoDB, E-commerce and TransactionsMongoDB, E-commerce and Transactions
MongoDB, E-commerce and Transactions
 
MongoDB, PHP and the cloud - php cloud summit 2011
MongoDB, PHP and the cloud - php cloud summit 2011MongoDB, PHP and the cloud - php cloud summit 2011
MongoDB, PHP and the cloud - php cloud summit 2011
 
MongoDB and PHP ZendCon 2011
MongoDB and PHP ZendCon 2011MongoDB and PHP ZendCon 2011
MongoDB and PHP ZendCon 2011
 
MongoDB
MongoDBMongoDB
MongoDB
 
Blending MongoDB and RDBMS for ecommerce
Blending MongoDB and RDBMS for ecommerceBlending MongoDB and RDBMS for ecommerce
Blending MongoDB and RDBMS for ecommerce
 
Augmenting RDBMS with MongoDB for ecommerce
Augmenting RDBMS with MongoDB for ecommerceAugmenting RDBMS with MongoDB for ecommerce
Augmenting RDBMS with MongoDB for ecommerce
 
MongoDB and Ecommerce : A perfect combination
MongoDB and Ecommerce : A perfect combinationMongoDB and Ecommerce : A perfect combination
MongoDB and Ecommerce : A perfect combination
 

Kürzlich hochgeladen

Secure your environment with UiPath and CyberArk technologies - Session 1
Secure your environment with UiPath and CyberArk technologies - Session 1Secure your environment with UiPath and CyberArk technologies - Session 1
Secure your environment with UiPath and CyberArk technologies - Session 1DianaGray10
 
UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6DianaGray10
 
UiPath Platform: The Backend Engine Powering Your Automation - Session 1
UiPath Platform: The Backend Engine Powering Your Automation - Session 1UiPath Platform: The Backend Engine Powering Your Automation - Session 1
UiPath Platform: The Backend Engine Powering Your Automation - Session 1DianaGray10
 
Meet the new FSP 3000 M-Flex800™
Meet the new FSP 3000 M-Flex800™Meet the new FSP 3000 M-Flex800™
Meet the new FSP 3000 M-Flex800™Adtran
 
VoIP Service and Marketing using Odoo and Asterisk PBX
VoIP Service and Marketing using Odoo and Asterisk PBXVoIP Service and Marketing using Odoo and Asterisk PBX
VoIP Service and Marketing using Odoo and Asterisk PBXTarek Kalaji
 
Machine Learning Model Validation (Aijun Zhang 2024).pdf
Machine Learning Model Validation (Aijun Zhang 2024).pdfMachine Learning Model Validation (Aijun Zhang 2024).pdf
Machine Learning Model Validation (Aijun Zhang 2024).pdfAijun Zhang
 
The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...
The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...
The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...Aggregage
 
activity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdf
activity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdf
activity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdfJamie (Taka) Wang
 
AI Fame Rush Review – Virtual Influencer Creation In Just Minutes
AI Fame Rush Review – Virtual Influencer Creation In Just MinutesAI Fame Rush Review – Virtual Influencer Creation In Just Minutes
AI Fame Rush Review – Virtual Influencer Creation In Just MinutesMd Hossain Ali
 
AI You Can Trust - Ensuring Success with Data Integrity Webinar
AI You Can Trust - Ensuring Success with Data Integrity WebinarAI You Can Trust - Ensuring Success with Data Integrity Webinar
AI You Can Trust - Ensuring Success with Data Integrity WebinarPrecisely
 
Using IESVE for Loads, Sizing and Heat Pump Modeling to Achieve Decarbonization
Using IESVE for Loads, Sizing and Heat Pump Modeling to Achieve DecarbonizationUsing IESVE for Loads, Sizing and Heat Pump Modeling to Achieve Decarbonization
Using IESVE for Loads, Sizing and Heat Pump Modeling to Achieve DecarbonizationIES VE
 
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPA
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPAAnypoint Code Builder , Google Pub sub connector and MuleSoft RPA
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPAshyamraj55
 
OpenShift Commons Paris - Choose Your Own Observability Adventure
OpenShift Commons Paris - Choose Your Own Observability AdventureOpenShift Commons Paris - Choose Your Own Observability Adventure
OpenShift Commons Paris - Choose Your Own Observability AdventureEric D. Schabell
 
Building AI-Driven Apps Using Semantic Kernel.pptx
Building AI-Driven Apps Using Semantic Kernel.pptxBuilding AI-Driven Apps Using Semantic Kernel.pptx
Building AI-Driven Apps Using Semantic Kernel.pptxUdaiappa Ramachandran
 
UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...
UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...
UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...UbiTrack UK
 
Empowering Africa's Next Generation: The AI Leadership Blueprint
Empowering Africa's Next Generation: The AI Leadership BlueprintEmpowering Africa's Next Generation: The AI Leadership Blueprint
Empowering Africa's Next Generation: The AI Leadership BlueprintMahmoud Rabie
 
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...DianaGray10
 
NIST Cybersecurity Framework (CSF) 2.0 Workshop
NIST Cybersecurity Framework (CSF) 2.0 WorkshopNIST Cybersecurity Framework (CSF) 2.0 Workshop
NIST Cybersecurity Framework (CSF) 2.0 WorkshopBachir Benyammi
 
COMPUTER 10: Lesson 7 - File Storage and Online Collaboration
COMPUTER 10: Lesson 7 - File Storage and Online CollaborationCOMPUTER 10: Lesson 7 - File Storage and Online Collaboration
COMPUTER 10: Lesson 7 - File Storage and Online Collaborationbruanjhuli
 
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...Will Schroeder
 

Kürzlich hochgeladen (20)

Secure your environment with UiPath and CyberArk technologies - Session 1
Secure your environment with UiPath and CyberArk technologies - Session 1Secure your environment with UiPath and CyberArk technologies - Session 1
Secure your environment with UiPath and CyberArk technologies - Session 1
 
UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6
 
UiPath Platform: The Backend Engine Powering Your Automation - Session 1
UiPath Platform: The Backend Engine Powering Your Automation - Session 1UiPath Platform: The Backend Engine Powering Your Automation - Session 1
UiPath Platform: The Backend Engine Powering Your Automation - Session 1
 
Meet the new FSP 3000 M-Flex800™
Meet the new FSP 3000 M-Flex800™Meet the new FSP 3000 M-Flex800™
Meet the new FSP 3000 M-Flex800™
 
VoIP Service and Marketing using Odoo and Asterisk PBX
VoIP Service and Marketing using Odoo and Asterisk PBXVoIP Service and Marketing using Odoo and Asterisk PBX
VoIP Service and Marketing using Odoo and Asterisk PBX
 
Machine Learning Model Validation (Aijun Zhang 2024).pdf
Machine Learning Model Validation (Aijun Zhang 2024).pdfMachine Learning Model Validation (Aijun Zhang 2024).pdf
Machine Learning Model Validation (Aijun Zhang 2024).pdf
 
The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...
The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...
The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...
 
activity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdf
activity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdf
activity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdf
 
AI Fame Rush Review – Virtual Influencer Creation In Just Minutes
AI Fame Rush Review – Virtual Influencer Creation In Just MinutesAI Fame Rush Review – Virtual Influencer Creation In Just Minutes
AI Fame Rush Review – Virtual Influencer Creation In Just Minutes
 
AI You Can Trust - Ensuring Success with Data Integrity Webinar
AI You Can Trust - Ensuring Success with Data Integrity WebinarAI You Can Trust - Ensuring Success with Data Integrity Webinar
AI You Can Trust - Ensuring Success with Data Integrity Webinar
 
Using IESVE for Loads, Sizing and Heat Pump Modeling to Achieve Decarbonization
Using IESVE for Loads, Sizing and Heat Pump Modeling to Achieve DecarbonizationUsing IESVE for Loads, Sizing and Heat Pump Modeling to Achieve Decarbonization
Using IESVE for Loads, Sizing and Heat Pump Modeling to Achieve Decarbonization
 
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPA
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPAAnypoint Code Builder , Google Pub sub connector and MuleSoft RPA
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPA
 
OpenShift Commons Paris - Choose Your Own Observability Adventure
OpenShift Commons Paris - Choose Your Own Observability AdventureOpenShift Commons Paris - Choose Your Own Observability Adventure
OpenShift Commons Paris - Choose Your Own Observability Adventure
 
Building AI-Driven Apps Using Semantic Kernel.pptx
Building AI-Driven Apps Using Semantic Kernel.pptxBuilding AI-Driven Apps Using Semantic Kernel.pptx
Building AI-Driven Apps Using Semantic Kernel.pptx
 
UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...
UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...
UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...
 
Empowering Africa's Next Generation: The AI Leadership Blueprint
Empowering Africa's Next Generation: The AI Leadership BlueprintEmpowering Africa's Next Generation: The AI Leadership Blueprint
Empowering Africa's Next Generation: The AI Leadership Blueprint
 
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
 
NIST Cybersecurity Framework (CSF) 2.0 Workshop
NIST Cybersecurity Framework (CSF) 2.0 WorkshopNIST Cybersecurity Framework (CSF) 2.0 Workshop
NIST Cybersecurity Framework (CSF) 2.0 Workshop
 
COMPUTER 10: Lesson 7 - File Storage and Online Collaboration
COMPUTER 10: Lesson 7 - File Storage and Online CollaborationCOMPUTER 10: Lesson 7 - File Storage and Online Collaboration
COMPUTER 10: Lesson 7 - File Storage and Online Collaboration
 
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
 

Go for Object Oriented Programmers or Object Oriented Programming without Objects

  • 1. Go for Object 
 Oriented Programmers ! or ! Object Oriented Programming 
 Without Objects
  • 2. • Author of Hugo, Cobra, Viper & More • Chief Developer Advocate for MongoDB • Gopher @spf13
  • 3. — txxxxd “Most of the appeal for me is not the features that Go has, but rather the features that have been intentionally left out.”
  • 4. — Rob Pike “Why would you have a language that is not theoretically exciting? Because it’s very useful.”
  • 6. Does Go have Objects? • Go lacks Classes • Go lacks “Objects”
  • 8. – Steve Francia “An object is an abstract data type that has state (data) and behavior (code).”
  • 9. type Rect struct { width int height int } Type Declaration (Struct)
  • 10. func (r *Rect) Area() int { return r.width * r.height } Declaring a Method
  • 11. func main() { r := Rect{width: 10, height: 5} fmt.Println("area: ", r.Area()) } In Action
  • 12. type Rects []Rect Type Declaration (Slice)
  • 13. func (rs Rects) Area() int { var a int for _, r := range rs { a += r.Area() } return a } Declaring a Method
  • 14. func main() { r := Rect{width: 10, height: 5} x := Rect{width: 7, height:10} rs := Rects{r, x} fmt.Println("r's area: ", r.Area()) fmt.Println("x's area: ", x.Area()) fmt.Println("total area: ", rs.Area()) } In Action http://play.golang.org/p/G1OWXPGvc3
  • 15. type Foo func() int Type Declaration (Func)
  • 16. func (f Foo) Add(x int) int { return f() + x } Declaring a Method
  • 17. func main() { var x Foo ! x = func() int { return 1 } ! fmt.Println(x()) fmt.Println(x.Add(3)) } In Action http://play.golang.org/p/YGrdCG3SlI
  • 20. – Wikipedia A language is usually considered object-based if it includes the basic capabilities for an object: identity, properties, and attributes. 
 A language is considered object-oriented if it is object-based and also has the capability of polymorphism and inheritance.
  • 21. Go is Object Based. ! Is it OO?
  • 22. Inheritance • Provides reuse of objects • Classes are created in hierarchies • Inheritance lets the structure and methods in one class pass down the hierarchy
  • 23. Go’s approach • Go explicitly avoided inheritance • Go strictly follows the composition over inheritance principle • Composition through embedded types
  • 24. Composition • Provides reuse of Objects • One object is declared by including other objects • Composition lets the structure and methods in one class be pulled into another
  • 25. – Steve Francia Inheritance passes “knowledge” down ! Composition pulls “knowledge” up
  • 26. type Person struct { Name string Address } ! ! type Address struct { Number string Street string City string State string Zip string } Embedding Types Inner Type
  • 27. func (a *Address) String() string { return a.Number+" "+a.Street+"n"+
 a.City+", "+a.State+" "+a.Zip+"n" } Declaring a Method
  • 28. func main() { p := Person{ Name: "Steve", Address: Address{ Number: "13", Street: "Main", City: "Gotham", State: "NY", Zip: "01313", }, } } Declare using Composite Literal
  • 29. func main() { p := Person{ Name: "Steve", Address: Address{ Number: "13", Street: "Main", City: "Gotham", State: "NY", Zip: "01313", }, } fmt.Println(p.String()) In Action http://play.golang.org/p/9beVY9jNlW
  • 30. Promotion • Promotion looks to see if a single inner type can satisify the request and “promotes” it • Embedded fields & methods are “promoted” • Promotion only occurs during usage, not declaration • Promoted methods are considered for interface adherance
  • 31. func (a *Address) String() string { return a.Number+" "+a.Street+"n"+
 a.City+", "+a.State+" "+a.Zip+"n" } ! func (p *Person) String() string { return p.Name + "n" + p.Address.String() } Not Overloading
  • 32. func main() { p := Person{ Name: "Steve", Address: Address{ Number: "13", Street: "Main", City: "Gotham", State: "NY", Zip: "01313", }, } ! fmt.Println(p.String()) fmt.Println(p.Address.String()) } Both Methods Available http://play.golang.org/p/Aui0nGa5Xi
  • 33. func isValidAddress(a *Address) bool { return a.Street != "" } ! func main() { p := Person{ Name: "Steve", Address: Address{ Number: "13", Street: "Main", City: "Gotham", State: "NY", Zip: "01313"}} ! fmt.Println(isValidAddress(p)) 
 // cannot use p (type Person) as type Address 
 // in argument to isValidAddress fmt.Println(isValidAddress(p.Address)) } Types Remain Distinct http://play.golang.org/p/KYjXZxNBcQ
  • 35. Polymorphism • “The provision of a single interface to entities of different types” • Typically implmented via Generics, Overloading and/or Subtyping
  • 36. Go’s approach • Go explicitly avoided subtyping & overloading • Go does not provide Generics (yet) • Go’s interface provide polymorphic capabilities
  • 37. Interfaces • A list of required methods • Structural vs Nominal typing • ‘‘If something can do this, then it can be used here” • Convention is call it a Something-er
  • 38. type Shaper interface { Area() int } Interface Declaration
  • 39. func Describe(s Shaper) { fmt.Println("Area is:", s.Area()) } Using Interface as Param Type
  • 40. func main() { r := &Rect{width: 10, height: 5} x := &Rect{width: 7, height: 10} rs := &Rects{r, x} Describe(r) Describe(x) Describe(rs) } In Action http://play.golang.org/p/WL77LihUwi
  • 41. –James Gosling (creator of Java) “If you could do Java over again, what would you change?” “I’d leave out classes,” he replied. After the laughter died down, he explained that the real problem wasn’t classes per se, but rather implementation inheritance (the extends relationship). Interface inheritance (the implements relationship) is preferable. You should avoid implementation inheritance whenever possible.
  • 42. Go Interfaces are based on implementation, not declaration
  • 44. type Reader interface { Read(p []byte) (n int, err error) } io.Reader
  • 45. io.Reader • Interface • Read reads up to len(p) bytes into p • Returns the # of bytes read & any error • Does not dictate how Read() is implemented • Used by os.File, bytes.Buffer, net.Conn, http.Request.Body, loads more
  • 46. type Writer interface { Write(p []byte) (n int, err error) } io.Writer
  • 47. io.Writer • Interface • Write writes up to len(p) bytes into p • Returns the # of bytes written & any error • Does not dictate how Write() is implemented • Used by os.File, bytes.Buffer, net.Conn, http.Response.Body, loads more
  • 48. func MarshalGzippedJSON(r io.Reader, 
 v interface{}) error { raw, err := gzip.NewReader(r) if err != nil { return err } return json.NewDecoder(raw).Decode(&v) } io.Reader in Action
  • 49. f, err := os.Open("myfile.json.gz") if err != nil { log.Fatalln(err) } defer f.Close() m = make(map[string]interface{}) MarshalGzippedJSON(f, &m) Reading a json.gz file
  • 50. Practical Interoperability • Gzip.NewReader(io.Reader) • Works on files, http requests, byte buffers, network connections, …anything you create • Nothing special needed in gzip to be able to do this… Simply call Read(n) and leave the abstracting to the implementor
  • 51. func main() { resp, err := http.Get("...") if err != nil { log.Fatalln(err) } defer resp.Body.Close() out, err := os.Create("filename.ext") if err != nil { log.Fatalln(err) } defer out.Close() io.Copy(out, resp.Body) // out io.Writer, resp.Body io.Reader } Pipe http response to file
  • 52. Go
  • 53. — Steve Jobs Simple can be harder than complex: You have to work hard to get your thinking clean to make it simple. But it's worth it in the end because once you get there, you can move mountains.
  • 54. Go is simple, pratical & wonderful