SlideShare a Scribd company logo
1 of 56
Download to read offline
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

More Related Content

What's hot

Node-v0.12の新機能について
Node-v0.12の新機能についてNode-v0.12の新機能について
Node-v0.12の新機能について
shigeki_ohtsu
 
Advanced Javascript
Advanced JavascriptAdvanced Javascript
Advanced Javascript
Adieu
 

What's hot (20)

NumPy.pptx
NumPy.pptxNumPy.pptx
NumPy.pptx
 
파이썬 플라스크 이해하기
파이썬 플라스크 이해하기 파이썬 플라스크 이해하기
파이썬 플라스크 이해하기
 
게임서버프로그래밍 #2 - IOCP Adv
게임서버프로그래밍 #2 - IOCP Adv게임서버프로그래밍 #2 - IOCP Adv
게임서버프로그래밍 #2 - IOCP Adv
 
Swagger / Quick Start Guide
Swagger / Quick Start GuideSwagger / Quick Start Guide
Swagger / Quick Start Guide
 
Golang
GolangGolang
Golang
 
Лекция 8. Графы. Обходы графов
Лекция 8. Графы. Обходы графовЛекция 8. Графы. Обходы графов
Лекция 8. Графы. Обходы графов
 
Idiomatic Kotlin
Idiomatic KotlinIdiomatic Kotlin
Idiomatic Kotlin
 
Node.js Express
Node.js  ExpressNode.js  Express
Node.js Express
 
Kotlinアンチパターン
KotlinアンチパターンKotlinアンチパターン
Kotlinアンチパターン
 
Node-v0.12の新機能について
Node-v0.12の新機能についてNode-v0.12の新機能について
Node-v0.12の新機能について
 
Go Lang Tutorial
Go Lang TutorialGo Lang Tutorial
Go Lang Tutorial
 
Rust Intro
Rust IntroRust Intro
Rust Intro
 
Advanced JavaScript
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScript
 
Using Vivox to connect your players: Text and voice comms – Unite Copenhagen ...
Using Vivox to connect your players: Text and voice comms – Unite Copenhagen ...Using Vivox to connect your players: Text and voice comms – Unite Copenhagen ...
Using Vivox to connect your players: Text and voice comms – Unite Copenhagen ...
 
RxJS - The Basics & The Future
RxJS - The Basics & The FutureRxJS - The Basics & The Future
RxJS - The Basics & The Future
 
Golang and Eco-System Introduction / Overview
Golang and Eco-System Introduction / OverviewGolang and Eco-System Introduction / Overview
Golang and Eco-System Introduction / Overview
 
Advanced Javascript
Advanced JavascriptAdvanced Javascript
Advanced Javascript
 
Mock and patch
Mock and patchMock and patch
Mock and patch
 
Golang workshop
Golang workshopGolang workshop
Golang workshop
 
Kotlin Bytecode Generation and Runtime Performance
Kotlin Bytecode Generation and Runtime PerformanceKotlin Bytecode Generation and Runtime Performance
Kotlin Bytecode Generation and Runtime Performance
 

Viewers also liked

OSCON 2012 MongoDB Tutorial
OSCON 2012 MongoDB TutorialOSCON 2012 MongoDB Tutorial
OSCON 2012 MongoDB Tutorial
Steven Francia
 
Object Oriented Concept
Object Oriented ConceptObject Oriented Concept
Object Oriented Concept
smj
 

Viewers also liked (20)

Painless Data Storage with MongoDB & Go
Painless Data Storage with MongoDB & Go Painless Data Storage with MongoDB & Go
Painless Data Storage with MongoDB & Go
 
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
 
Getting Started with Go
Getting Started with GoGetting Started with Go
Getting Started with Go
 
7 Common mistakes in Go and when to avoid them
7 Common mistakes in Go and when to avoid them7 Common mistakes in Go and when to avoid them
7 Common mistakes in Go and when to avoid them
 
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
 
A Recovering Java Developer Learns to Go
A Recovering Java Developer Learns to GoA Recovering Java Developer Learns to Go
A Recovering Java Developer Learns to Go
 
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
 

Similar to Go for Object Oriented Programmers or Object Oriented Programming without Objects

Denis Lebedev, Swift
Denis  Lebedev, SwiftDenis  Lebedev, Swift
Denis Lebedev, Swift
Yandex
 
json.ppt download for free for college project
json.ppt download for free for college projectjson.ppt download for free for college project
json.ppt download for free for college project
AmitSharma397241
 
The Kotlin Programming Language
The Kotlin Programming LanguageThe Kotlin Programming Language
The Kotlin Programming Language
intelliyole
 

Similar to 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
 
json.ppt download for free for college project
json.ppt download for free for college projectjson.ppt download for free for college project
json.ppt download for free for college project
 
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
 

More from Steven Francia

MongoDB, Hadoop and Humongous Data
MongoDB, Hadoop and Humongous DataMongoDB, Hadoop and Humongous Data
MongoDB, Hadoop and Humongous Data
Steven Francia
 
Hybrid MongoDB and RDBMS Applications
Hybrid MongoDB and RDBMS ApplicationsHybrid MongoDB and RDBMS Applications
Hybrid MongoDB and RDBMS Applications
Steven Francia
 
MongoDB and PHP ZendCon 2011
MongoDB and PHP ZendCon 2011MongoDB and PHP ZendCon 2011
MongoDB and PHP ZendCon 2011
Steven Francia
 
Blending MongoDB and RDBMS for ecommerce
Blending MongoDB and RDBMS for ecommerceBlending MongoDB and RDBMS for ecommerce
Blending MongoDB and RDBMS for ecommerce
Steven Francia
 

More from 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
 

Recently uploaded

IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
Enterprise Knowledge
 

Recently uploaded (20)

Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 

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