SlideShare uma empresa Scribd logo
1 de 37
Happy Programming with Go Compiler
GTG 12
poga
Today
• Tricks to write DSL in Go
• code generation with GO GENERATE
DSL in Go
s.Config(
LogLevel(WARN),
Backend(S3{
Key: "API_KEY",
Secret: "SUPER SECRET",
}),
AfterComplete(func() {
fmt.Println("service ready")
}),
)
Do(With{A: "foo", B: 123})
Ruby
• DSL!
• Slow



Ruby
• DSL!
• Slow
• Error-prone
DSL in Ruby
DSL in Ruby
validates :name, presence: true
validate :name, presence: true
validates :name, presense: true
Which is correct?
DSL in Ruby
validates :points, numericality: true
validates :points, numericality: { only: “integer” }
validates :points, numericality: { only_integer: true }
Which is correct?
DSL in Ruby
• String/symbol + Hash everywhere
• lack of “Syntax Error”
• everything is void*
• anything is ok for ruby interpreter
• Need a lot of GOOD documentation

DSL in Ruby
• String/symbol + Hash everywhere
• lack of “Syntax Error”
• everything is void*
• anything is ok for ruby interpreter
• Need a lot of GOOD documentation
• and memorization
Go
• Fast
• Small Footprint



















Go
• Fast
• Small Footprint
• Verbose
• sort
• if err != nil
• if err != nil
• if err != nil
Patterns
• http://www.godesignpatterns.com/
• https://blog.golang.org/errors-are-values
Named Parameter
type With struct {
A string
B int
}
func main() {
Do(With{A: "foo", B: 123})
}
func Do(p With) {
…
}
Named Parameter
• Error when
• mistype parameter name
• incorrect parameter type
Configuration
s.Config(
LogLevel(WARN),
Backend(S3{
Key: "API_KEY",
Secret: "SUPER SECRET",
}),
AfterComplete(func() {
fmt.Println("service ready")
}),
)
type Service struct {
ErrorLevel int
AWSKey string
AWSSecret string
AfterHook func()
}
https://gist.github.com/poga/bf0534486199c8e778cb
Configuration
• Self-referential Function



















type option func(*Service)
func (s *Service) Config(opts ...option) {
for _, opt := range opts {
opt(s)
}
}
func LogLevel(level int) option {
return func(s *Service) {
s.ErrorLevel = level
}
}
http://commandcenter.blogspot.com.au/2014/01/self-referential-functions-and-design.html
Struct Tag
type Person struct {
FirstName string `json:"first_name"`
LastName string `json:"last_name"`
MiddleName string `json:"middle_name,omitempty"`
}
Struct Tag
• Anti-Pattern
• String-typing
• No compile time checking
• 6 month old bug in KKTIX production, no one noticed
• based on reflect
• slow
• Don’t use it as DSL
Vanilla Go
• Sometimes it’s not enough
• We need to go deeper













Code Generation
WOW
So Rails
Much Magic
Error Handling in Go
• Extremely Verbose
• We already have 3 official error handling patterns
• https://blog.golang.org/errors-are-values
• checking error is fine. But I’m lazy to type
• Messy control flow
Error Handler Generation
• go get github.com/poga/autoerror
• just a demo, don’t use it in production
Auto Error
• Add error checking function
based on the name of error
variable
• Hide error checking from
control flow
//go:generate autoerror -i simple.go -t AutoError -o test.go
type AutoError error
var e AutoError
var e2 AutoError
func Test() {
e = doSomething()
e2 = doSomething()
}
func doSomething() error {
return errors.New("an error")
}
func handleError2(e2 error) {
if e2 != nil {
panic(e)
}
}
func handleError(e error) {
if e != nil {
panic(e)
}
}
//go:generate autoerror -i simple.go -t AutoError -o test.go
type AutoError error
var e AutoError
var e2 AutoError
func Test() {
e = doSomething()
e2 = doSomething()
}
func doSomething() error {
return errors.New("an error")
}
func handleError2(e2 error) {
if e2 != nil {
panic(e)
}
}
func handleError(e error) {
if e != nil {
panic(e)
}
}
//go:generate autoerror -i simple.go -t AutoError -o test.go
type AutoError error
var e AutoError
var e2 AutoError
func Test() {
e = doSomething()
e2 = doSomething()
handleError2(e2)
}
func doSomething() error {
return errors.New("an error")
}
func handleError2(e2 error) {
if e2 != nil {
panic(e)
}
}
func handleError(e error) {
if e != nil {
panic(e)
}
}
//go:generate autoerror -i simple.go -t AutoError -o test.go
type AutoError error
var e AutoError
var e2 AutoError
func Test() {
e = doSomething()
e2 = doSomething()
handleError2(e2)
}
func doSomething() error {
return errors.New("an error")
}
func handleError2(e2 error) {
if e2 != nil {
panic(e)
}
}
func handleError(e error) {
if e != nil {
panic(e)
}
}
//go:generate autoerror -i simple.go -t AutoError -o test.go
type AutoError error
var e AutoError
var e2 AutoError
func Test() {
e = doSomething()
handleError(e)
e2 = doSomething()
handleError2(e2)
}
func doSomething() error {
return errors.New("an error")
}
func handleError2(e2 error) {
if e2 != nil {
panic(e)
}
}
func handleError(e error) {
if e != nil {
panic(e)
}
}
What is Go Generate
• shell scripting in go









$ go generate
//go:generate echo 'hello from go generate'
hello from go generate
go generate
• execute a ruby script
• integrate with code gen tools
• yacc, protocol buffer,… etc
//go:generate ruby gen.rb
//go:generate codecgen -o values.generated.go file1.go file2.go file3.go
go generate
• go get won’t execute ‘go generate’ for you
• generate before publish
type checking placeholder
json.have(
pair{Key: “FirstName”, From: “first_name”},
pair{Key: “FirstName”, From: “first_name”},
pair{Key: “MiddleName”, From: “middle_name”, OmitEmpty: true})
type Person struct {
FirstName string `json:"first_name"`
LastName string `json:"last_name"`
MiddleName string `json:"middle_name,omitempty"`
}
person.have(
string{Key: “FirstName”, From: “first_name”},
string{Key: “FirstName”, From: “first_name”},
string{Key: “MiddleName”, From: “middle_name”, OmitEmpty: true})
type Person struct {
FirstName string `json:"first_name"`
LastName string `json:"last_name"`
MiddleName string `json:"middle_name,omitempty"`
}
func (p Person) have(pairs pair…) {
panic(“run go generate before use this file”)
}
Recap
• DSL
• Named Parameter
• Configuration
• Code Generation
• type checking placeholder
Thank you

Mais conteúdo relacionado

Mais procurados

Nightwatch at Tilt
Nightwatch at TiltNightwatch at Tilt
Nightwatch at TiltDave King
 
Build a bot workshop async primer - php[tek]
Build a bot workshop  async primer - php[tek]Build a bot workshop  async primer - php[tek]
Build a bot workshop async primer - php[tek]Adam Englander
 
Angular Application Testing
Angular Application TestingAngular Application Testing
Angular Application TestingTroy Miles
 
ZendCon 2017 - Build a Bot Workshop - Async Primer
ZendCon 2017 - Build a Bot Workshop - Async PrimerZendCon 2017 - Build a Bot Workshop - Async Primer
ZendCon 2017 - Build a Bot Workshop - Async PrimerAdam Englander
 
Optimizing a large angular application (ng conf)
Optimizing a large angular application (ng conf)Optimizing a large angular application (ng conf)
Optimizing a large angular application (ng conf)A K M Zahiduzzaman
 
20160905 - BrisJS - nightwatch testing
20160905 - BrisJS - nightwatch testing20160905 - BrisJS - nightwatch testing
20160905 - BrisJS - nightwatch testingVladimir Roudakov
 
CodePolitan Webinar: The Rise of PHP
CodePolitan Webinar: The Rise of PHPCodePolitan Webinar: The Rise of PHP
CodePolitan Webinar: The Rise of PHPSteeven Salim
 
Unit testing JavaScript using Mocha and Node
Unit testing JavaScript using Mocha and NodeUnit testing JavaScript using Mocha and Node
Unit testing JavaScript using Mocha and NodeJosh Mock
 
Unit testing with mocha
Unit testing with mochaUnit testing with mocha
Unit testing with mochaRevath S Kumar
 
Python for AngularJS
Python for AngularJSPython for AngularJS
Python for AngularJSJeff Schenck
 
Lets make a better react form
Lets make a better react formLets make a better react form
Lets make a better react formYao Nien Chung
 
I18n
I18nI18n
I18nsoon
 
Callbacks, promises, generators - asynchronous javascript
Callbacks, promises, generators - asynchronous javascriptCallbacks, promises, generators - asynchronous javascript
Callbacks, promises, generators - asynchronous javascriptŁukasz Kużyński
 
Low Latency Logging with RabbitMQ (PHP London - 4th Sep 2014)
Low Latency Logging with RabbitMQ (PHP London - 4th Sep 2014)Low Latency Logging with RabbitMQ (PHP London - 4th Sep 2014)
Low Latency Logging with RabbitMQ (PHP London - 4th Sep 2014)James Titcumb
 
Low Latency Logging with RabbitMQ (Brno PHP, CZ - 20th Sep 2014)
Low Latency Logging with RabbitMQ (Brno PHP, CZ - 20th Sep 2014)Low Latency Logging with RabbitMQ (Brno PHP, CZ - 20th Sep 2014)
Low Latency Logging with RabbitMQ (Brno PHP, CZ - 20th Sep 2014)James Titcumb
 
High Performance web apps in Om, React and ClojureScript
High Performance web apps in Om, React and ClojureScriptHigh Performance web apps in Om, React and ClojureScript
High Performance web apps in Om, React and ClojureScriptLeonardo Borges
 
Enhance react app with patterns - part 1: higher order component
Enhance react app with patterns - part 1: higher order componentEnhance react app with patterns - part 1: higher order component
Enhance react app with patterns - part 1: higher order componentYao Nien Chung
 

Mais procurados (20)

Nightwatch at Tilt
Nightwatch at TiltNightwatch at Tilt
Nightwatch at Tilt
 
Build a bot workshop async primer - php[tek]
Build a bot workshop  async primer - php[tek]Build a bot workshop  async primer - php[tek]
Build a bot workshop async primer - php[tek]
 
Angular Application Testing
Angular Application TestingAngular Application Testing
Angular Application Testing
 
ZendCon 2017 - Build a Bot Workshop - Async Primer
ZendCon 2017 - Build a Bot Workshop - Async PrimerZendCon 2017 - Build a Bot Workshop - Async Primer
ZendCon 2017 - Build a Bot Workshop - Async Primer
 
Optimizing a large angular application (ng conf)
Optimizing a large angular application (ng conf)Optimizing a large angular application (ng conf)
Optimizing a large angular application (ng conf)
 
20160905 - BrisJS - nightwatch testing
20160905 - BrisJS - nightwatch testing20160905 - BrisJS - nightwatch testing
20160905 - BrisJS - nightwatch testing
 
CodePolitan Webinar: The Rise of PHP
CodePolitan Webinar: The Rise of PHPCodePolitan Webinar: The Rise of PHP
CodePolitan Webinar: The Rise of PHP
 
Unit testing JavaScript using Mocha and Node
Unit testing JavaScript using Mocha and NodeUnit testing JavaScript using Mocha and Node
Unit testing JavaScript using Mocha and Node
 
Unit testing with mocha
Unit testing with mochaUnit testing with mocha
Unit testing with mocha
 
Python for AngularJS
Python for AngularJSPython for AngularJS
Python for AngularJS
 
Lets make a better react form
Lets make a better react formLets make a better react form
Lets make a better react form
 
I18n
I18nI18n
I18n
 
Callbacks, promises, generators - asynchronous javascript
Callbacks, promises, generators - asynchronous javascriptCallbacks, promises, generators - asynchronous javascript
Callbacks, promises, generators - asynchronous javascript
 
第26回PHP勉強会
第26回PHP勉強会第26回PHP勉強会
第26回PHP勉強会
 
Your code are my tests
Your code are my testsYour code are my tests
Your code are my tests
 
Low Latency Logging with RabbitMQ (PHP London - 4th Sep 2014)
Low Latency Logging with RabbitMQ (PHP London - 4th Sep 2014)Low Latency Logging with RabbitMQ (PHP London - 4th Sep 2014)
Low Latency Logging with RabbitMQ (PHP London - 4th Sep 2014)
 
You promise?
You promise?You promise?
You promise?
 
Low Latency Logging with RabbitMQ (Brno PHP, CZ - 20th Sep 2014)
Low Latency Logging with RabbitMQ (Brno PHP, CZ - 20th Sep 2014)Low Latency Logging with RabbitMQ (Brno PHP, CZ - 20th Sep 2014)
Low Latency Logging with RabbitMQ (Brno PHP, CZ - 20th Sep 2014)
 
High Performance web apps in Om, React and ClojureScript
High Performance web apps in Om, React and ClojureScriptHigh Performance web apps in Om, React and ClojureScript
High Performance web apps in Om, React and ClojureScript
 
Enhance react app with patterns - part 1: higher order component
Enhance react app with patterns - part 1: higher order componentEnhance react app with patterns - part 1: higher order component
Enhance react app with patterns - part 1: higher order component
 

Destaque

萬事萬物皆是 LOG - 系統架構也來點科普
萬事萬物皆是 LOG - 系統架構也來點科普萬事萬物皆是 LOG - 系統架構也來點科普
萬事萬物皆是 LOG - 系統架構也來點科普Poga Po
 
聽說 KKTIX 都是用 Go 寫的 - ModernWeb 2015
聽說 KKTIX 都是用 Go 寫的 - ModernWeb 2015聽說 KKTIX 都是用 Go 寫的 - ModernWeb 2015
聽說 KKTIX 都是用 Go 寫的 - ModernWeb 2015Poga Po
 
Full-stack go with GopherJS
Full-stack go with GopherJSFull-stack go with GopherJS
Full-stack go with GopherJSPoga Po
 
OSDC.TW - Gutscript for PHP haters
OSDC.TW - Gutscript for PHP hatersOSDC.TW - Gutscript for PHP haters
OSDC.TW - Gutscript for PHP hatersLin Yo-An
 
Use go channel to write a disk queue
Use go channel to write a disk queueUse go channel to write a disk queue
Use go channel to write a disk queueEvan Lin
 

Destaque (7)

Wtt#20
Wtt#20Wtt#20
Wtt#20
 
萬事萬物皆是 LOG - 系統架構也來點科普
萬事萬物皆是 LOG - 系統架構也來點科普萬事萬物皆是 LOG - 系統架構也來點科普
萬事萬物皆是 LOG - 系統架構也來點科普
 
聽說 KKTIX 都是用 Go 寫的 - ModernWeb 2015
聽說 KKTIX 都是用 Go 寫的 - ModernWeb 2015聽說 KKTIX 都是用 Go 寫的 - ModernWeb 2015
聽說 KKTIX 都是用 Go 寫的 - ModernWeb 2015
 
Full-stack go with GopherJS
Full-stack go with GopherJSFull-stack go with GopherJS
Full-stack go with GopherJS
 
OSDC.TW - Gutscript for PHP haters
OSDC.TW - Gutscript for PHP hatersOSDC.TW - Gutscript for PHP haters
OSDC.TW - Gutscript for PHP haters
 
Goqt
GoqtGoqt
Goqt
 
Use go channel to write a disk queue
Use go channel to write a disk queueUse go channel to write a disk queue
Use go channel to write a disk queue
 

Semelhante a Gtg12

Exception Handling: Designing Robust Software in Ruby
Exception Handling: Designing Robust Software in RubyException Handling: Designing Robust Software in Ruby
Exception Handling: Designing Robust Software in RubyWen-Tien Chang
 
Efficient JavaScript Development
Efficient JavaScript DevelopmentEfficient JavaScript Development
Efficient JavaScript Developmentwolframkriesing
 
JavaScript in 2015
JavaScript in 2015JavaScript in 2015
JavaScript in 2015Igor Laborie
 
Lecture 03 - JQuery.pdf
Lecture 03 - JQuery.pdfLecture 03 - JQuery.pdf
Lecture 03 - JQuery.pdfLê Thưởng
 
Angularjs Test Driven Development (TDD)
Angularjs Test Driven Development (TDD)Angularjs Test Driven Development (TDD)
Angularjs Test Driven Development (TDD)Anis Bouhachem Djer
 
Compatibility Detector Tool of Chrome extensions
Compatibility Detector Tool of Chrome extensionsCompatibility Detector Tool of Chrome extensions
Compatibility Detector Tool of Chrome extensionsKai Cui
 
Go 1.10 Release Party - PDX Go
Go 1.10 Release Party - PDX GoGo 1.10 Release Party - PDX Go
Go 1.10 Release Party - PDX GoRodolfo Carvalho
 
Test-Driven Development of AngularJS Applications
Test-Driven Development of AngularJS ApplicationsTest-Driven Development of AngularJS Applications
Test-Driven Development of AngularJS ApplicationsFITC
 
How Testability Inspires AngularJS Design / Ran Mizrahi
How Testability Inspires AngularJS Design / Ran MizrahiHow Testability Inspires AngularJS Design / Ran Mizrahi
How Testability Inspires AngularJS Design / Ran MizrahiRan Mizrahi
 
ECMAScript.Next ECMAScipt 6
ECMAScript.Next ECMAScipt 6ECMAScript.Next ECMAScipt 6
ECMAScript.Next ECMAScipt 6Kevin DeRudder
 
What's up with Prototype and script.aculo.us?
What's up with Prototype and script.aculo.us?What's up with Prototype and script.aculo.us?
What's up with Prototype and script.aculo.us?Christophe Porteneuve
 
Jest: Frontend Testing richtig gemacht @WebworkerNRW
Jest: Frontend Testing richtig gemacht @WebworkerNRWJest: Frontend Testing richtig gemacht @WebworkerNRW
Jest: Frontend Testing richtig gemacht @WebworkerNRWHolger Grosse-Plankermann
 
Efficient JavaScript Development
Efficient JavaScript DevelopmentEfficient JavaScript Development
Efficient JavaScript Developmentwolframkriesing
 
Everything-as-code - A polyglot adventure
Everything-as-code - A polyglot adventureEverything-as-code - A polyglot adventure
Everything-as-code - A polyglot adventureQAware GmbH
 
Everything-as-code. A polyglot adventure. #DevoxxPL
Everything-as-code. A polyglot adventure. #DevoxxPLEverything-as-code. A polyglot adventure. #DevoxxPL
Everything-as-code. A polyglot adventure. #DevoxxPLMario-Leander Reimer
 
.gradle 파일 정독해보기
.gradle 파일 정독해보기.gradle 파일 정독해보기
.gradle 파일 정독해보기경주 전
 
An Introduction To jQuery
An Introduction To jQueryAn Introduction To jQuery
An Introduction To jQueryAndy Gibson
 

Semelhante a Gtg12 (20)

Exception Handling: Designing Robust Software in Ruby
Exception Handling: Designing Robust Software in RubyException Handling: Designing Robust Software in Ruby
Exception Handling: Designing Robust Software in Ruby
 
Efficient JavaScript Development
Efficient JavaScript DevelopmentEfficient JavaScript Development
Efficient JavaScript Development
 
JavaScript in 2015
JavaScript in 2015JavaScript in 2015
JavaScript in 2015
 
All things that are not code
All things that are not codeAll things that are not code
All things that are not code
 
Lecture 03 - JQuery.pdf
Lecture 03 - JQuery.pdfLecture 03 - JQuery.pdf
Lecture 03 - JQuery.pdf
 
Angularjs Test Driven Development (TDD)
Angularjs Test Driven Development (TDD)Angularjs Test Driven Development (TDD)
Angularjs Test Driven Development (TDD)
 
Compatibility Detector Tool of Chrome extensions
Compatibility Detector Tool of Chrome extensionsCompatibility Detector Tool of Chrome extensions
Compatibility Detector Tool of Chrome extensions
 
Go 1.10 Release Party - PDX Go
Go 1.10 Release Party - PDX GoGo 1.10 Release Party - PDX Go
Go 1.10 Release Party - PDX Go
 
Test-Driven Development of AngularJS Applications
Test-Driven Development of AngularJS ApplicationsTest-Driven Development of AngularJS Applications
Test-Driven Development of AngularJS Applications
 
How Testability Inspires AngularJS Design / Ran Mizrahi
How Testability Inspires AngularJS Design / Ran MizrahiHow Testability Inspires AngularJS Design / Ran Mizrahi
How Testability Inspires AngularJS Design / Ran Mizrahi
 
Djangocon
DjangoconDjangocon
Djangocon
 
ECMAScript.Next ECMAScipt 6
ECMAScript.Next ECMAScipt 6ECMAScript.Next ECMAScipt 6
ECMAScript.Next ECMAScipt 6
 
Es.next
Es.nextEs.next
Es.next
 
What's up with Prototype and script.aculo.us?
What's up with Prototype and script.aculo.us?What's up with Prototype and script.aculo.us?
What's up with Prototype and script.aculo.us?
 
Jest: Frontend Testing richtig gemacht @WebworkerNRW
Jest: Frontend Testing richtig gemacht @WebworkerNRWJest: Frontend Testing richtig gemacht @WebworkerNRW
Jest: Frontend Testing richtig gemacht @WebworkerNRW
 
Efficient JavaScript Development
Efficient JavaScript DevelopmentEfficient JavaScript Development
Efficient JavaScript Development
 
Everything-as-code - A polyglot adventure
Everything-as-code - A polyglot adventureEverything-as-code - A polyglot adventure
Everything-as-code - A polyglot adventure
 
Everything-as-code. A polyglot adventure. #DevoxxPL
Everything-as-code. A polyglot adventure. #DevoxxPLEverything-as-code. A polyglot adventure. #DevoxxPL
Everything-as-code. A polyglot adventure. #DevoxxPL
 
.gradle 파일 정독해보기
.gradle 파일 정독해보기.gradle 파일 정독해보기
.gradle 파일 정독해보기
 
An Introduction To jQuery
An Introduction To jQueryAn Introduction To jQuery
An Introduction To jQuery
 

Último

Innovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdfInnovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdfYashikaSharma391629
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Mater
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalLionel Briand
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based projectAnoyGreter
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...confluent
 
PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentationvaddepallysandeep122
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationBradBedford3
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesŁukasz Chruściel
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanyChristoph Pohl
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfFerryKemperman
 
How To Manage Restaurant Staff -BTRESTRO
How To Manage Restaurant Staff -BTRESTROHow To Manage Restaurant Staff -BTRESTRO
How To Manage Restaurant Staff -BTRESTROmotivationalword821
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commercemanigoyal112
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtimeandrehoraa
 
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxUI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxAndreas Kunz
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...Technogeeks
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Cizo Technology Services
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Andreas Granig
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesPhilip Schwarz
 

Último (20)

Innovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdfInnovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdf
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive Goal
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based project
 
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort ServiceHot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
 
PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentation
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion Application
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New Features
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdf
 
How To Manage Restaurant Staff -BTRESTRO
How To Manage Restaurant Staff -BTRESTROHow To Manage Restaurant Staff -BTRESTRO
How To Manage Restaurant Staff -BTRESTRO
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commerce
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtime
 
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxUI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a series
 

Gtg12

  • 1. Happy Programming with Go Compiler GTG 12 poga
  • 2.
  • 3. Today • Tricks to write DSL in Go • code generation with GO GENERATE
  • 4. DSL in Go s.Config( LogLevel(WARN), Backend(S3{ Key: "API_KEY", Secret: "SUPER SECRET", }), AfterComplete(func() { fmt.Println("service ready") }), ) Do(With{A: "foo", B: 123})
  • 8. DSL in Ruby validates :name, presence: true validate :name, presence: true validates :name, presense: true Which is correct?
  • 9. DSL in Ruby validates :points, numericality: true validates :points, numericality: { only: “integer” } validates :points, numericality: { only_integer: true } Which is correct?
  • 10. DSL in Ruby • String/symbol + Hash everywhere • lack of “Syntax Error” • everything is void* • anything is ok for ruby interpreter • Need a lot of GOOD documentation

  • 11. DSL in Ruby • String/symbol + Hash everywhere • lack of “Syntax Error” • everything is void* • anything is ok for ruby interpreter • Need a lot of GOOD documentation • and memorization
  • 12. Go • Fast • Small Footprint
 
 
 
 
 
 
 
 
 

  • 13. Go • Fast • Small Footprint • Verbose • sort • if err != nil • if err != nil • if err != nil
  • 15. Named Parameter type With struct { A string B int } func main() { Do(With{A: "foo", B: 123}) } func Do(p With) { … }
  • 16. Named Parameter • Error when • mistype parameter name • incorrect parameter type
  • 17. Configuration s.Config( LogLevel(WARN), Backend(S3{ Key: "API_KEY", Secret: "SUPER SECRET", }), AfterComplete(func() { fmt.Println("service ready") }), ) type Service struct { ErrorLevel int AWSKey string AWSSecret string AfterHook func() } https://gist.github.com/poga/bf0534486199c8e778cb
  • 18. Configuration • Self-referential Function
 
 
 
 
 
 
 
 
 
 type option func(*Service) func (s *Service) Config(opts ...option) { for _, opt := range opts { opt(s) } } func LogLevel(level int) option { return func(s *Service) { s.ErrorLevel = level } } http://commandcenter.blogspot.com.au/2014/01/self-referential-functions-and-design.html
  • 19. Struct Tag type Person struct { FirstName string `json:"first_name"` LastName string `json:"last_name"` MiddleName string `json:"middle_name,omitempty"` }
  • 20. Struct Tag • Anti-Pattern • String-typing • No compile time checking • 6 month old bug in KKTIX production, no one noticed • based on reflect • slow • Don’t use it as DSL
  • 21. Vanilla Go • Sometimes it’s not enough • We need to go deeper
 
 
 
 
 
 

  • 23. Error Handling in Go • Extremely Verbose • We already have 3 official error handling patterns • https://blog.golang.org/errors-are-values • checking error is fine. But I’m lazy to type • Messy control flow
  • 24. Error Handler Generation • go get github.com/poga/autoerror • just a demo, don’t use it in production
  • 25. Auto Error • Add error checking function based on the name of error variable • Hide error checking from control flow
  • 26. //go:generate autoerror -i simple.go -t AutoError -o test.go type AutoError error var e AutoError var e2 AutoError func Test() { e = doSomething() e2 = doSomething() } func doSomething() error { return errors.New("an error") } func handleError2(e2 error) { if e2 != nil { panic(e) } } func handleError(e error) { if e != nil { panic(e) } }
  • 27. //go:generate autoerror -i simple.go -t AutoError -o test.go type AutoError error var e AutoError var e2 AutoError func Test() { e = doSomething() e2 = doSomething() } func doSomething() error { return errors.New("an error") } func handleError2(e2 error) { if e2 != nil { panic(e) } } func handleError(e error) { if e != nil { panic(e) } }
  • 28. //go:generate autoerror -i simple.go -t AutoError -o test.go type AutoError error var e AutoError var e2 AutoError func Test() { e = doSomething() e2 = doSomething() handleError2(e2) } func doSomething() error { return errors.New("an error") } func handleError2(e2 error) { if e2 != nil { panic(e) } } func handleError(e error) { if e != nil { panic(e) } }
  • 29. //go:generate autoerror -i simple.go -t AutoError -o test.go type AutoError error var e AutoError var e2 AutoError func Test() { e = doSomething() e2 = doSomething() handleError2(e2) } func doSomething() error { return errors.New("an error") } func handleError2(e2 error) { if e2 != nil { panic(e) } } func handleError(e error) { if e != nil { panic(e) } }
  • 30. //go:generate autoerror -i simple.go -t AutoError -o test.go type AutoError error var e AutoError var e2 AutoError func Test() { e = doSomething() handleError(e) e2 = doSomething() handleError2(e2) } func doSomething() error { return errors.New("an error") } func handleError2(e2 error) { if e2 != nil { panic(e) } } func handleError(e error) { if e != nil { panic(e) } }
  • 31. What is Go Generate • shell scripting in go
 
 
 
 
 $ go generate //go:generate echo 'hello from go generate' hello from go generate
  • 32. go generate • execute a ruby script • integrate with code gen tools • yacc, protocol buffer,… etc //go:generate ruby gen.rb //go:generate codecgen -o values.generated.go file1.go file2.go file3.go
  • 33. go generate • go get won’t execute ‘go generate’ for you • generate before publish
  • 34. type checking placeholder json.have( pair{Key: “FirstName”, From: “first_name”}, pair{Key: “FirstName”, From: “first_name”}, pair{Key: “MiddleName”, From: “middle_name”, OmitEmpty: true}) type Person struct { FirstName string `json:"first_name"` LastName string `json:"last_name"` MiddleName string `json:"middle_name,omitempty"` }
  • 35. person.have( string{Key: “FirstName”, From: “first_name”}, string{Key: “FirstName”, From: “first_name”}, string{Key: “MiddleName”, From: “middle_name”, OmitEmpty: true}) type Person struct { FirstName string `json:"first_name"` LastName string `json:"last_name"` MiddleName string `json:"middle_name,omitempty"` } func (p Person) have(pairs pair…) { panic(“run go generate before use this file”) }
  • 36. Recap • DSL • Named Parameter • Configuration • Code Generation • type checking placeholder