SlideShare ist ein Scribd-Unternehmen logo
1 von 34
Downloaden Sie, um offline zu lesen
Object-Oriented Programming in
Go
Go Seoul Meetup
24 January 2015
장재휴
Developer, Purpleworks
Who am I
Elandsystems ➜ purpleworks
Ruby, C#, Go
Agenda
OOP in Go
What is "Object Oriented" (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
Is Go Object-based Language?
What is an "Object" (wikipedia)
An object is an abstract data type that has state(data) and behavior(code)
Object in Go (via Custom Type & Method)
package main
import "fmt"
// Type Declaration
type Item struct {type Item struct {
name string
price float64
quantity int
}
// Method Declaration
func (t Item) Cost() float64 {func (t Item) Cost() float64 {
return t.price * float64(t.quantity)
}
// In Action
func main() {
shirt := Item{name: "Men's Slim-Fit Shirt", price: 25000, quantity: 3}
fmt.Println("cost: ", shirt.Cost())fmt.Println("cost: ", shirt.Cost())
} Run
Custom Type of built-in Type
// Type Declaration
type Items []Itemtype Items []Item
// Method Declaration
func (ts Items) Cost() float64 {func (ts Items) Cost() float64 {
var c float64
for _, t := range ts {
c += t.Cost()
}
return c
}
// In Action
func main() {
shirt := Item{name: "Men's Slim-Fit Shirt", price: 25000, quantity: 3}
shoes := Item{name: "Sports Shoes", price: 30000, quantity: 2}
items := Items{shirt, shoes}
fmt.Println("cost of shirt: ", shirt.Cost())
fmt.Println("cost of shoes: ", shoes.Cost())
fmt.Println("total cost: ", items.Cost())
} Run
Go is Object-based
Via custom type and methods
Is Go Object-oriented Language?
What is "Inheritance" (wikipedia)
Provides reuse of existing objects
Classes are created in hierarchies
Inheritance passes knowledge down!
Inheritance is not good
In Java user group meeting,
James Gosling (Java’s inventor) says:
You should avoid implementation inheritance whenever possible.
Go's approach
Go avoided inheritance
Go strictly follows the Composition over inheritance principle
What is Composition
Provides reuse of Objects
One object is declared by containing other objects
Composition pulls knowledge into another
Composition in Go
// Type Declaration
type Item struct {
name string
price float64
quantity int
}
type DiscountItem struct {
ItemItem
discountRate float64
}
// In Action
func main() {
shoes := Item{name: "Sports Shoes", price: 30000, quantity: 2}
eventShoes := DiscountItem{eventShoes := DiscountItem{
Item{name: "Women's Walking Shoes", price: 50000, quantity: 3},Item{name: "Women's Walking Shoes", price: 50000, quantity: 3},
10.00,10.00,
}}
fmt.Println("shoes: ", shoes)
fmt.Println("eventShoes: ", eventShoes)
} Run
Call Method of Embedded Type
type DiscountItem struct {
Item
discountRate float64
}
// Method Declaration
func (t Item) Cost() float64 {func (t Item) Cost() float64 {
return t.price * float64(t.quantity)return t.price * float64(t.quantity)
}}
// In Action
func main() {
shoes := Item{name: "Sports Shoes", price: 30000, quantity: 2}
eventShoes := DiscountItem{
Item{name: "Women's Walking Shoes", price: 50000, quantity: 3},
10.00,
}
fmt.Println("cost of shoes: ", shoes.Cost())fmt.Println("cost of shoes: ", shoes.Cost())
fmt.Println("cost of eventShoes: ", eventShoes.Cost())fmt.Println("cost of eventShoes: ", eventShoes.Cost())
} Run
Method Overriding
// Method Declaration
func (t Item) Cost() float64 {
return t.price * float64(t.quantity)
}
func (t DiscountItem) Cost() float64 {func (t DiscountItem) Cost() float64 {
return t.Item.Cost() * (1.0 - t.discountRate/100)return t.Item.Cost() * (1.0 - t.discountRate/100)
}}
// In Action
func main() {
shoes := Item{name: "Sports Shoes", price: 30000, quantity: 2}
eventShoes := DiscountItem{
Item{name: "Women's Walking Shoes", price: 50000, quantity: 3},
10.00,
}
fmt.Println("cost of shoes: ", shoes.Cost())
fmt.Println("cost of eventShoes: ", eventShoes.Cost())
} Run
Composition in Go 2
// Type Declaration (embedded field)
type Order struct {
ItemsItems
taxRate float64
}
// Overriding Methods
func (o Order) Cost() float64 {func (o Order) Cost() float64 {
return o.Items.Cost() * (1.0 + o.taxRate/100)
}
func main() {
shirt := Item{name: "Men's Slim-Fit Shirt", price: 25000, quantity: 3}
shoes := Item{name: "Sports Shoes", price: 30000, quantity: 2}
items := Items{shirt, shoes}
order := Order{Items: items, taxRate: 10.00}
fmt.Println("cost of shirt: ", shirt.Cost())
fmt.Println("cost of shoes: ", shoes.Cost())
fmt.Println("total cost: ", items.Cost())
fmt.Println("total cost(included Tax): ", order.Cost())
} Run
Composition in Go 3
func main() {
shirt := Item{name: "Men's Slim-Fit Shirt", price: 25000, quantity: 3}
shoes := Item{name: "Sports Shoes", price: 30000, quantity: 2}
eventShoes := DiscountItem{
Item{name: "Women's Walking Shoes", price: 50000, quantity: 3},
10.00,
}
items := Items{shirt, shoes, eventShoes}
order := Order{Items: items, taxRate: 10.00}
fmt.Println("cost of shirt: ", shirt.Cost())
fmt.Println("cost of shoes: ", shoes.Cost())
fmt.Println("cost of eventShoes: ", eventShoes.Cost())
fmt.Println("total cost: ", items.Cost())
fmt.Println("total cost(included Tax): ", order.Cost())
} Run
Composition in Go 4
func main() {
shirt := Item{name: "Men's Slim-Fit Shirt", price: 25000, quantity: 3}
shoes := Item{name: "Sports Shoes", price: 30000, quantity: 2}
eventShoes := DiscountItem{
Item{name: "Women's Walking Shoes", price: 50000, quantity: 3},
10.00,
}
items := Items{shirt, shoes, eventShoes}
order := Order{Items: items, taxRate: 10.00}
fmt.Println("cost of shirt: ", shirt.Cost())
fmt.Println("cost of shoes: ", shoes.Cost())
fmt.Println("cost of eventShoes: ", eventShoes.Cost())
fmt.Println("total cost: ", items.Cost())
fmt.Println("total cost(included Tax): ", order.Cost())
} Run
What is "Polymorphism" (wikipedia)
The provision of a single interface to entities of different types
Via Generics, Overloading and/or Subtyping
Go’s approach
Go avoided subtyping & overloading
Go does not provide Generics
Polymorphism via interfaces
Interfaces in Go
Interfaces are just sets of methods
Interfaces define behavior (duck typing)
"If something can do this, then it can be used here”
Interfaces in Go
type Rental struct {
name string
feePerDay float64
periodLength int
RentalPeriod
}
type RentalPeriod int
const (
Days RentalPeriod = iota
Weeks
Months
)
func (p RentalPeriod) ToDays() int {
switch p {
case Weeks:
return 7
case Months:
return 30
default:
return 1
}
}
Interfaces in Go
func (r Rental) Cost() float64 {
return r.feePerDay * float64(r.ToDays()*r.periodLength)
}
// Interface Declaration
type Coster interface {type Coster interface {
Cost() float64Cost() float64
}}
func DisplayCost(c Coster) {func DisplayCost(c Coster) {
fmt.Println("cost: ", c.Cost())
}
// In Action
func main() {
shirt := Item{name: "Men's Slim-Fit Shirt", price: 25000, quantity: 3}
video := Rental{"Interstellar", 1000, 3, Days}
fmt.Printf("[%v] ", shirt.name)
DisplayCost(shirt)DisplayCost(shirt)
fmt.Printf("[%v] ", video.name)
DisplayCost(video)DisplayCost(video)
} Run
Interfaces in Go 2
// Interface Declaration
type Coster interface {
Cost() float64
}
// Items
type Items []Costertype Items []Coster
func main() {
shirt := Item{name: "Men's Slim-Fit Shirt", price: 25000, quantity: 3}
video := Rental{"Interstellar", 1000, 3, Days}
eventShoes := DiscountItem{
Item{name: "Women's Walking Shoes", price: 50000, quantity: 3},
10.00,
}
items := Items{shirt, video, eventShoes}
order := Order{Items: items, taxRate: 10.00}
DisplayCost(shirt)
DisplayCost(video)
DisplayCost(eventShoes)
DisplayCost(items)
DisplayCost(order)
}
Run
Satisfying Interface of Other Package
fmt.Println
func Println(a ...interface{}) (n int, err error) {
return Fprintln(os.Stdout, a...)
}
func Fprintln(w io.Writer, a ...interface{}) (n int, err error) {
...
// print using Stringer interface
...
return
}
fmt.Stringer
type Stringer interface {
String() string
}
Satisfying Interface of Other Package
// Stringer
func (t Item) String() string {
return fmt.Sprintf("[%s] %.0f", t.name, t.Cost())
}
func (t Rental) String() string {
return fmt.Sprintf("[%s] %.0f", t.name, t.Cost())
}
func (t DiscountItem) String() string {
return fmt.Sprintf("%s => %.0f(%.0f%s DC)", t.Item.String(), t.Cost(), t.discountRate, "%")
}
func (t Items) String() string {
return fmt.Sprintf("%d items. total: %.0f", len(t), t.Cost())
}
func (o Order) String() string {
return fmt.Sprintf("Include Tax: %.0f(tax rate: %.2f%s)", o.Cost(), o.taxRate, "%")
}
Satisfying Interface of Other Package
func main() {
shirt := Item{name: "Men's Slim-Fit Shirt", price: 25000, quantity: 3}
video := Rental{"Interstellar", 1000, 3, Days}
eventShoes := DiscountItem{
Item{name: "Women's Walking Shoes", price: 50000, quantity: 3},
10.00,
}
items := Items{shirt, video, eventShoes}
order := Order{Items: items, taxRate: 10.00}
fmt.Println(shirt)
fmt.Println(video)
fmt.Println(eventShoes)
fmt.Println(items)
fmt.Println(order)
} Run
Deep into Go's Standard Library
io.Writer interface
// http://godoc.org/io#Writer
type Writer interface {
Write(p []byte) (n int, err os.Error)
}
fmt.Fprintln function
func Fprintln(w io.Writer, a ...interface{}) (n int, err error)
The Power of Interfaces
In handle function, just write to io.Writer object
func handle(w io.Writer, msg string) {
fmt.Fprintln(w, msg)
}
The os.Stdout can be used for io.Writer.
func main() {
msg := []string{"hello", "world", "this", "is", "an", "example", "of", "io.Writer"}
for _, s := range msg {
time.Sleep(100 * time.Millisecond)
handle(os.Stdout, s)handle(os.Stdout, s)
}
} Run
The Power of Interfaces
The http.ResponseWriter can be used for io.Writer.
localhost:4000/hello-world(http://localhost:4000/hello-world)
localhost:4000/this-is-an-example-of-io.Writer(http://localhost:4000/this-is-an-example-of-io.Writer)
func handle(w io.Writer, msg string) {
fmt.Fprintln(w, msg)
}
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
handle(w, r.URL.Path[1:])handle(w, r.URL.Path[1:])
})
fmt.Println("start listening on port 4000")
http.ListenAndServe(":4000", nil)
} Run
Go is Object-Oriented
Thank you
장재휴
Developer, Purpleworks
jaehue@jang.io(mailto:jaehue@jang.io)

Weitere ähnliche Inhalte

Was ist angesagt?

Type safe embedded domain-specific languages
Type safe embedded domain-specific languagesType safe embedded domain-specific languages
Type safe embedded domain-specific languagesArthur Xavier
 
Productaccess m
Productaccess mProductaccess m
Productaccess mAdil Usman
 
Chapter 8- Advanced Views and URLconfs
Chapter 8- Advanced Views and URLconfsChapter 8- Advanced Views and URLconfs
Chapter 8- Advanced Views and URLconfsVincent Chien
 
Stamps - a better way to object composition
Stamps - a better way to object compositionStamps - a better way to object composition
Stamps - a better way to object compositionVasyl Boroviak
 
JavaScript - i och utanför webbläsaren (2010-03-03)
JavaScript - i och utanför webbläsaren (2010-03-03)JavaScript - i och utanför webbläsaren (2010-03-03)
JavaScript - i och utanför webbläsaren (2010-03-03)Anders Jönsson
 
Imugi: Compiler made with Python
Imugi: Compiler made with PythonImugi: Compiler made with Python
Imugi: Compiler made with PythonHan Lee
 
Using semi-structured data in modern applications
Using semi-structured data in modern applicationsUsing semi-structured data in modern applications
Using semi-structured data in modern applicationsMariaDB plc
 
Programming Language Swift Overview
Programming Language Swift OverviewProgramming Language Swift Overview
Programming Language Swift OverviewKaz Yoshikawa
 
Fundamental JS
Fundamental JSFundamental JS
Fundamental JSXiming Dai
 
Moving to hybrid relational/JSON data models
Moving to hybrid relational/JSON data modelsMoving to hybrid relational/JSON data models
Moving to hybrid relational/JSON data modelsMariaDB plc
 
Hybrid Data Models - Relational + JSON
Hybrid Data Models - Relational + JSONHybrid Data Models - Relational + JSON
Hybrid Data Models - Relational + JSONDATAVERSITY
 
Event Sourcing and Functional Programming
Event Sourcing and Functional ProgrammingEvent Sourcing and Functional Programming
Event Sourcing and Functional ProgrammingGlobalLogic Ukraine
 
Effector: we need to go deeper
Effector: we need to go deeperEffector: we need to go deeper
Effector: we need to go deeperVictor Didenko
 
Swift 함수 커링 사용하기
Swift 함수 커링 사용하기Swift 함수 커링 사용하기
Swift 함수 커링 사용하기진성 오
 
Javasccript MV* frameworks
Javasccript MV* frameworksJavasccript MV* frameworks
Javasccript MV* frameworksKerry Buckley
 
Introduction to ad-3.4, an automatic differentiation library in Haskell
Introduction to ad-3.4, an automatic differentiation library in HaskellIntroduction to ad-3.4, an automatic differentiation library in Haskell
Introduction to ad-3.4, an automatic differentiation library in Haskellnebuta
 

Was ist angesagt? (20)

Type safe embedded domain-specific languages
Type safe embedded domain-specific languagesType safe embedded domain-specific languages
Type safe embedded domain-specific languages
 
Productaccess m
Productaccess mProductaccess m
Productaccess m
 
Prototype UI Intro
Prototype UI IntroPrototype UI Intro
Prototype UI Intro
 
Part 7
Part 7Part 7
Part 7
 
Chapter 8- Advanced Views and URLconfs
Chapter 8- Advanced Views and URLconfsChapter 8- Advanced Views and URLconfs
Chapter 8- Advanced Views and URLconfs
 
Stamps - a better way to object composition
Stamps - a better way to object compositionStamps - a better way to object composition
Stamps - a better way to object composition
 
JavaScript - i och utanför webbläsaren (2010-03-03)
JavaScript - i och utanför webbläsaren (2010-03-03)JavaScript - i och utanför webbläsaren (2010-03-03)
JavaScript - i och utanför webbläsaren (2010-03-03)
 
Imugi: Compiler made with Python
Imugi: Compiler made with PythonImugi: Compiler made with Python
Imugi: Compiler made with Python
 
Using semi-structured data in modern applications
Using semi-structured data in modern applicationsUsing semi-structured data in modern applications
Using semi-structured data in modern applications
 
Programming Language Swift Overview
Programming Language Swift OverviewProgramming Language Swift Overview
Programming Language Swift Overview
 
Fundamental JS
Fundamental JSFundamental JS
Fundamental JS
 
Moving to hybrid relational/JSON data models
Moving to hybrid relational/JSON data modelsMoving to hybrid relational/JSON data models
Moving to hybrid relational/JSON data models
 
Hybrid Data Models - Relational + JSON
Hybrid Data Models - Relational + JSONHybrid Data Models - Relational + JSON
Hybrid Data Models - Relational + JSON
 
Event Sourcing and Functional Programming
Event Sourcing and Functional ProgrammingEvent Sourcing and Functional Programming
Event Sourcing and Functional Programming
 
Effector: we need to go deeper
Effector: we need to go deeperEffector: we need to go deeper
Effector: we need to go deeper
 
Swift 함수 커링 사용하기
Swift 함수 커링 사용하기Swift 함수 커링 사용하기
Swift 함수 커링 사용하기
 
Javasccript MV* frameworks
Javasccript MV* frameworksJavasccript MV* frameworks
Javasccript MV* frameworks
 
Introduction to ad-3.4, an automatic differentiation library in Haskell
Introduction to ad-3.4, an automatic differentiation library in HaskellIntroduction to ad-3.4, an automatic differentiation library in Haskell
Introduction to ad-3.4, an automatic differentiation library in Haskell
 
Developing iOS apps with Swift
Developing iOS apps with SwiftDeveloping iOS apps with Swift
Developing iOS apps with Swift
 
Groovy intro for OUDL
Groovy intro for OUDLGroovy intro for OUDL
Groovy intro for OUDL
 

Ähnlich wie Object oriented programming in go

Introduction to Go
Introduction to GoIntroduction to Go
Introduction to GoJaehue Jang
 
JavaScript Objects and OOP Programming with JavaScript
JavaScript Objects and OOP Programming with JavaScriptJavaScript Objects and OOP Programming with JavaScript
JavaScript Objects and OOP Programming with JavaScriptLaurence Svekis ✔
 
Go ahead, make my day
Go ahead, make my dayGo ahead, make my day
Go ahead, make my dayTor Ivry
 
Django 1.1 Tour
Django 1.1 TourDjango 1.1 Tour
Django 1.1 TourIdan Gazit
 
A sighting of traverse_ function in Practical FP in Scala
A sighting of traverse_ function in Practical FP in ScalaA sighting of traverse_ function in Practical FP in Scala
A sighting of traverse_ function in Practical FP in ScalaPhilip Schwarz
 
Generics and Inference
Generics and InferenceGenerics and Inference
Generics and InferenceRichard Fox
 
mobl presentation @ IHomer
mobl presentation @ IHomermobl presentation @ IHomer
mobl presentation @ IHomerzefhemel
 
The Ring programming language version 1.5.4 book - Part 40 of 185
The Ring programming language version 1.5.4 book - Part 40 of 185The Ring programming language version 1.5.4 book - Part 40 of 185
The Ring programming language version 1.5.4 book - Part 40 of 185Mahmoud Samir Fayed
 
Functional Programming & Event Sourcing - a pair made in heaven
Functional Programming & Event Sourcing - a pair made in heavenFunctional Programming & Event Sourcing - a pair made in heaven
Functional Programming & Event Sourcing - a pair made in heavenPawel Szulc
 
Using a mobile phone as a therapist - Superweek 2018
Using a mobile phone as a therapist - Superweek 2018Using a mobile phone as a therapist - Superweek 2018
Using a mobile phone as a therapist - Superweek 2018Peter Meyer
 
mobl - model-driven engineering lecture
mobl - model-driven engineering lecturemobl - model-driven engineering lecture
mobl - model-driven engineering lecturezefhemel
 
Greyhound - Powerful Pure Functional Kafka Library - Scala Love in the City
Greyhound - Powerful Pure Functional Kafka Library - Scala Love in the CityGreyhound - Powerful Pure Functional Kafka Library - Scala Love in the City
Greyhound - Powerful Pure Functional Kafka Library - Scala Love in the CityNatan Silnitsky
 
Improving Correctness With Type - Goto Con Berlin
Improving Correctness With Type - Goto Con BerlinImproving Correctness With Type - Goto Con Berlin
Improving Correctness With Type - Goto Con BerlinIain Hull
 

Ähnlich wie Object oriented programming in go (20)

Introduction to Go
Introduction to GoIntroduction to Go
Introduction to Go
 
JavaScript Objects and OOP Programming with JavaScript
JavaScript Objects and OOP Programming with JavaScriptJavaScript Objects and OOP Programming with JavaScript
JavaScript Objects and OOP Programming with JavaScript
 
Go ahead, make my day
Go ahead, make my dayGo ahead, make my day
Go ahead, make my day
 
Leveraging Symfony2 Forms
Leveraging Symfony2 FormsLeveraging Symfony2 Forms
Leveraging Symfony2 Forms
 
Django 1.1 Tour
Django 1.1 TourDjango 1.1 Tour
Django 1.1 Tour
 
Functional DDD
Functional DDDFunctional DDD
Functional DDD
 
Fun with functions
Fun with functionsFun with functions
Fun with functions
 
A sighting of traverse_ function in Practical FP in Scala
A sighting of traverse_ function in Practical FP in ScalaA sighting of traverse_ function in Practical FP in Scala
A sighting of traverse_ function in Practical FP in Scala
 
Generics and Inference
Generics and InferenceGenerics and Inference
Generics and Inference
 
Introduction to Go for Java Programmers
Introduction to Go for Java ProgrammersIntroduction to Go for Java Programmers
Introduction to Go for Java Programmers
 
mobl presentation @ IHomer
mobl presentation @ IHomermobl presentation @ IHomer
mobl presentation @ IHomer
 
The Ring programming language version 1.5.4 book - Part 40 of 185
The Ring programming language version 1.5.4 book - Part 40 of 185The Ring programming language version 1.5.4 book - Part 40 of 185
The Ring programming language version 1.5.4 book - Part 40 of 185
 
mobl
moblmobl
mobl
 
Functional Programming & Event Sourcing - a pair made in heaven
Functional Programming & Event Sourcing - a pair made in heavenFunctional Programming & Event Sourcing - a pair made in heaven
Functional Programming & Event Sourcing - a pair made in heaven
 
Using a mobile phone as a therapist - Superweek 2018
Using a mobile phone as a therapist - Superweek 2018Using a mobile phone as a therapist - Superweek 2018
Using a mobile phone as a therapist - Superweek 2018
 
mobl - model-driven engineering lecture
mobl - model-driven engineering lecturemobl - model-driven engineering lecture
mobl - model-driven engineering lecture
 
Build your own entity with Drupal
Build your own entity with DrupalBuild your own entity with Drupal
Build your own entity with Drupal
 
Greyhound - Powerful Pure Functional Kafka Library - Scala Love in the City
Greyhound - Powerful Pure Functional Kafka Library - Scala Love in the CityGreyhound - Powerful Pure Functional Kafka Library - Scala Love in the City
Greyhound - Powerful Pure Functional Kafka Library - Scala Love in the City
 
Kotlin, why?
Kotlin, why?Kotlin, why?
Kotlin, why?
 
Improving Correctness With Type - Goto Con Berlin
Improving Correctness With Type - Goto Con BerlinImproving Correctness With Type - Goto Con Berlin
Improving Correctness With Type - Goto Con Berlin
 

Kürzlich hochgeladen

call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about usDynamic Netsoft
 
Clustering techniques data mining book ....
Clustering techniques data mining book ....Clustering techniques data mining book ....
Clustering techniques data mining book ....ShaimaaMohamedGalal
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️anilsa9823
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AIABDERRAOUF MEHENNI
 
Test Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendTest Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendArshad QA
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 

Kürzlich hochgeladen (20)

call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about us
 
Clustering techniques data mining book ....
Clustering techniques data mining book ....Clustering techniques data mining book ....
Clustering techniques data mining book ....
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
Test Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendTest Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and Backend
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 

Object oriented programming in go

  • 1. Object-Oriented Programming in Go Go Seoul Meetup 24 January 2015 장재휴 Developer, Purpleworks
  • 2. Who am I Elandsystems ➜ purpleworks Ruby, C#, Go
  • 4. What is "Object Oriented" (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
  • 5. Is Go Object-based Language?
  • 6. What is an "Object" (wikipedia) An object is an abstract data type that has state(data) and behavior(code)
  • 7. Object in Go (via Custom Type & Method) package main import "fmt" // Type Declaration type Item struct {type Item struct { name string price float64 quantity int } // Method Declaration func (t Item) Cost() float64 {func (t Item) Cost() float64 { return t.price * float64(t.quantity) } // In Action func main() { shirt := Item{name: "Men's Slim-Fit Shirt", price: 25000, quantity: 3} fmt.Println("cost: ", shirt.Cost())fmt.Println("cost: ", shirt.Cost()) } Run
  • 8. Custom Type of built-in Type // Type Declaration type Items []Itemtype Items []Item // Method Declaration func (ts Items) Cost() float64 {func (ts Items) Cost() float64 { var c float64 for _, t := range ts { c += t.Cost() } return c } // In Action func main() { shirt := Item{name: "Men's Slim-Fit Shirt", price: 25000, quantity: 3} shoes := Item{name: "Sports Shoes", price: 30000, quantity: 2} items := Items{shirt, shoes} fmt.Println("cost of shirt: ", shirt.Cost()) fmt.Println("cost of shoes: ", shoes.Cost()) fmt.Println("total cost: ", items.Cost()) } Run
  • 9. Go is Object-based Via custom type and methods
  • 11. What is "Inheritance" (wikipedia) Provides reuse of existing objects Classes are created in hierarchies Inheritance passes knowledge down!
  • 12. Inheritance is not good In Java user group meeting, James Gosling (Java’s inventor) says: You should avoid implementation inheritance whenever possible.
  • 13. Go's approach Go avoided inheritance Go strictly follows the Composition over inheritance principle
  • 14. What is Composition Provides reuse of Objects One object is declared by containing other objects Composition pulls knowledge into another
  • 15. Composition in Go // Type Declaration type Item struct { name string price float64 quantity int } type DiscountItem struct { ItemItem discountRate float64 } // In Action func main() { shoes := Item{name: "Sports Shoes", price: 30000, quantity: 2} eventShoes := DiscountItem{eventShoes := DiscountItem{ Item{name: "Women's Walking Shoes", price: 50000, quantity: 3},Item{name: "Women's Walking Shoes", price: 50000, quantity: 3}, 10.00,10.00, }} fmt.Println("shoes: ", shoes) fmt.Println("eventShoes: ", eventShoes) } Run
  • 16. Call Method of Embedded Type type DiscountItem struct { Item discountRate float64 } // Method Declaration func (t Item) Cost() float64 {func (t Item) Cost() float64 { return t.price * float64(t.quantity)return t.price * float64(t.quantity) }} // In Action func main() { shoes := Item{name: "Sports Shoes", price: 30000, quantity: 2} eventShoes := DiscountItem{ Item{name: "Women's Walking Shoes", price: 50000, quantity: 3}, 10.00, } fmt.Println("cost of shoes: ", shoes.Cost())fmt.Println("cost of shoes: ", shoes.Cost()) fmt.Println("cost of eventShoes: ", eventShoes.Cost())fmt.Println("cost of eventShoes: ", eventShoes.Cost()) } Run
  • 17. Method Overriding // Method Declaration func (t Item) Cost() float64 { return t.price * float64(t.quantity) } func (t DiscountItem) Cost() float64 {func (t DiscountItem) Cost() float64 { return t.Item.Cost() * (1.0 - t.discountRate/100)return t.Item.Cost() * (1.0 - t.discountRate/100) }} // In Action func main() { shoes := Item{name: "Sports Shoes", price: 30000, quantity: 2} eventShoes := DiscountItem{ Item{name: "Women's Walking Shoes", price: 50000, quantity: 3}, 10.00, } fmt.Println("cost of shoes: ", shoes.Cost()) fmt.Println("cost of eventShoes: ", eventShoes.Cost()) } Run
  • 18. Composition in Go 2 // Type Declaration (embedded field) type Order struct { ItemsItems taxRate float64 } // Overriding Methods func (o Order) Cost() float64 {func (o Order) Cost() float64 { return o.Items.Cost() * (1.0 + o.taxRate/100) } func main() { shirt := Item{name: "Men's Slim-Fit Shirt", price: 25000, quantity: 3} shoes := Item{name: "Sports Shoes", price: 30000, quantity: 2} items := Items{shirt, shoes} order := Order{Items: items, taxRate: 10.00} fmt.Println("cost of shirt: ", shirt.Cost()) fmt.Println("cost of shoes: ", shoes.Cost()) fmt.Println("total cost: ", items.Cost()) fmt.Println("total cost(included Tax): ", order.Cost()) } Run
  • 19. Composition in Go 3 func main() { shirt := Item{name: "Men's Slim-Fit Shirt", price: 25000, quantity: 3} shoes := Item{name: "Sports Shoes", price: 30000, quantity: 2} eventShoes := DiscountItem{ Item{name: "Women's Walking Shoes", price: 50000, quantity: 3}, 10.00, } items := Items{shirt, shoes, eventShoes} order := Order{Items: items, taxRate: 10.00} fmt.Println("cost of shirt: ", shirt.Cost()) fmt.Println("cost of shoes: ", shoes.Cost()) fmt.Println("cost of eventShoes: ", eventShoes.Cost()) fmt.Println("total cost: ", items.Cost()) fmt.Println("total cost(included Tax): ", order.Cost()) } Run
  • 20. Composition in Go 4 func main() { shirt := Item{name: "Men's Slim-Fit Shirt", price: 25000, quantity: 3} shoes := Item{name: "Sports Shoes", price: 30000, quantity: 2} eventShoes := DiscountItem{ Item{name: "Women's Walking Shoes", price: 50000, quantity: 3}, 10.00, } items := Items{shirt, shoes, eventShoes} order := Order{Items: items, taxRate: 10.00} fmt.Println("cost of shirt: ", shirt.Cost()) fmt.Println("cost of shoes: ", shoes.Cost()) fmt.Println("cost of eventShoes: ", eventShoes.Cost()) fmt.Println("total cost: ", items.Cost()) fmt.Println("total cost(included Tax): ", order.Cost()) } Run
  • 21. What is "Polymorphism" (wikipedia) The provision of a single interface to entities of different types Via Generics, Overloading and/or Subtyping
  • 22. Go’s approach Go avoided subtyping & overloading Go does not provide Generics Polymorphism via interfaces
  • 23. Interfaces in Go Interfaces are just sets of methods Interfaces define behavior (duck typing) "If something can do this, then it can be used here”
  • 24. Interfaces in Go type Rental struct { name string feePerDay float64 periodLength int RentalPeriod } type RentalPeriod int const ( Days RentalPeriod = iota Weeks Months ) func (p RentalPeriod) ToDays() int { switch p { case Weeks: return 7 case Months: return 30 default: return 1 } }
  • 25. Interfaces in Go func (r Rental) Cost() float64 { return r.feePerDay * float64(r.ToDays()*r.periodLength) } // Interface Declaration type Coster interface {type Coster interface { Cost() float64Cost() float64 }} func DisplayCost(c Coster) {func DisplayCost(c Coster) { fmt.Println("cost: ", c.Cost()) } // In Action func main() { shirt := Item{name: "Men's Slim-Fit Shirt", price: 25000, quantity: 3} video := Rental{"Interstellar", 1000, 3, Days} fmt.Printf("[%v] ", shirt.name) DisplayCost(shirt)DisplayCost(shirt) fmt.Printf("[%v] ", video.name) DisplayCost(video)DisplayCost(video) } Run
  • 26. Interfaces in Go 2 // Interface Declaration type Coster interface { Cost() float64 } // Items type Items []Costertype Items []Coster func main() { shirt := Item{name: "Men's Slim-Fit Shirt", price: 25000, quantity: 3} video := Rental{"Interstellar", 1000, 3, Days} eventShoes := DiscountItem{ Item{name: "Women's Walking Shoes", price: 50000, quantity: 3}, 10.00, } items := Items{shirt, video, eventShoes} order := Order{Items: items, taxRate: 10.00} DisplayCost(shirt) DisplayCost(video) DisplayCost(eventShoes) DisplayCost(items) DisplayCost(order) } Run
  • 27. Satisfying Interface of Other Package fmt.Println func Println(a ...interface{}) (n int, err error) { return Fprintln(os.Stdout, a...) } func Fprintln(w io.Writer, a ...interface{}) (n int, err error) { ... // print using Stringer interface ... return } fmt.Stringer type Stringer interface { String() string }
  • 28. Satisfying Interface of Other Package // Stringer func (t Item) String() string { return fmt.Sprintf("[%s] %.0f", t.name, t.Cost()) } func (t Rental) String() string { return fmt.Sprintf("[%s] %.0f", t.name, t.Cost()) } func (t DiscountItem) String() string { return fmt.Sprintf("%s => %.0f(%.0f%s DC)", t.Item.String(), t.Cost(), t.discountRate, "%") } func (t Items) String() string { return fmt.Sprintf("%d items. total: %.0f", len(t), t.Cost()) } func (o Order) String() string { return fmt.Sprintf("Include Tax: %.0f(tax rate: %.2f%s)", o.Cost(), o.taxRate, "%") }
  • 29. Satisfying Interface of Other Package func main() { shirt := Item{name: "Men's Slim-Fit Shirt", price: 25000, quantity: 3} video := Rental{"Interstellar", 1000, 3, Days} eventShoes := DiscountItem{ Item{name: "Women's Walking Shoes", price: 50000, quantity: 3}, 10.00, } items := Items{shirt, video, eventShoes} order := Order{Items: items, taxRate: 10.00} fmt.Println(shirt) fmt.Println(video) fmt.Println(eventShoes) fmt.Println(items) fmt.Println(order) } Run
  • 30. Deep into Go's Standard Library io.Writer interface // http://godoc.org/io#Writer type Writer interface { Write(p []byte) (n int, err os.Error) } fmt.Fprintln function func Fprintln(w io.Writer, a ...interface{}) (n int, err error)
  • 31. The Power of Interfaces In handle function, just write to io.Writer object func handle(w io.Writer, msg string) { fmt.Fprintln(w, msg) } The os.Stdout can be used for io.Writer. func main() { msg := []string{"hello", "world", "this", "is", "an", "example", "of", "io.Writer"} for _, s := range msg { time.Sleep(100 * time.Millisecond) handle(os.Stdout, s)handle(os.Stdout, s) } } Run
  • 32. The Power of Interfaces The http.ResponseWriter can be used for io.Writer. localhost:4000/hello-world(http://localhost:4000/hello-world) localhost:4000/this-is-an-example-of-io.Writer(http://localhost:4000/this-is-an-example-of-io.Writer) func handle(w io.Writer, msg string) { fmt.Fprintln(w, msg) } func main() { http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { handle(w, r.URL.Path[1:])handle(w, r.URL.Path[1:]) }) fmt.Println("start listening on port 4000") http.ListenAndServe(":4000", nil) } Run