SlideShare una empresa de Scribd logo
1 de 29
Descargar para leer sin conexión
Maintainable Go
Cherie Hsieh
Outline
o Naming
o Declaration Style
o Packages
o Design pattern
o
Naming
func startServer(host string, config *Config)
func startServer(host string, c *Config)
userMap := make(map[string]*User)
users := make(map[string]*User)
func CountFemale(people []Person) int {
c := 0
for i, p := range people {
if p.gender == "F" {
c++
}
}
return c
}
How to make variable names more clear?
Short Names
o Where the types are descriptive, they should be short.
o Where the types are more ambiguous, the names may provide
documentation.
o The greater the distance between a name's declaration and
its uses, the longer the name should be.
- Andrew Google Inc. What‘s in a name?
Short Names
o Single letter for method receivers, loops and branches.
o Single words for parameters and local variables.
o Two words for methods.
Short Names
o ‘i' to index
o ‘w’ to writer
o ‘r’ to reader
o ‘b’ to buffer
o ‘ok’ check if the key exists in the map
Names without their types
usersMap := make(map[string]*User)
users := make(map[string]*User) Preferred
o The name of the variable should describe its contents,
not the type of the contents.
- Dave Cheney. Practical Go
Names
Use a consistent naming style
A good name is it should be predictable
- Dave Cheney. Practical Go
Declaration Style
Declaration Style
var – Declare a variable without initialization
:= - Declare and initialize a variable
var stdnt Student Preferred
stdnt := Student{Name: "Cherie"}
stdnt := Student{}
Declaration Style
o nil Slice and non-nil Slice
var stdnts []Student Preferred
stdnts = make([]Student, 0) // For encoding JSON objects
Packages
Packages
o Do not put all types inside a models folder.
o Avoid package names like base, common, or util.
Its name doesn’t reflect its purpose, only its function in
breaking the import cycle.
Packages
o Avoid mutable package-global state
It is difficult to write unit tests.
May cause bugs in complex projects.
Packages
o Avoid a rigid project structure.
API Design
API Design
o Avoid taking several parameters of the same type.
// Example:
func Extract(source, target, destination string) error {
// Implementation
}
APIs with multiple parameters of the same type are hard to
use correctly. - Dave Cheney
API Design
o Carefully using nil as parameters.
// Bad
func DoSomething(cfg *customConfig) {
if cfg == nil {
// Use default config
}
}
DoSomething(nil)
Design pattern
Functional options
o A common way to apply your configuration
type Configuration struct {
Port int
Addr string
}
func NewServer(config *Configuration) {
//
}
Functional options
func NewServer(opts ...Option) {
cfg := Configuration{
Port: 8080,
Addr: "localhost"
}
// Use option functions to modify your default configuration
for _, opt := range opts {
opt(&cfg)
}
}
func ChangePort(v int) Option {
return func(cfg *Configuration){
cfg.Port = v
}
}
o A better way by using functional options
Functional options
// Example - gRPC
s := grpc.NewServer(grpc.StatsHandler(&ocgrpc.ServerHandler{}))
// Example - MongoDB
client, err := mongo.NewClient(options.Client().ApplyURI(”.."))
Dependency Injection
// Example
func main() {
cfg := GetConfig()
db, err := ConnectDatabase(cfg.URN)
if err != nil {
panic(err)
}
repo := NewPersonRepository(db)
service := NewPersonService(cfg.AccessToken, repo)
server := NewServer(cfg.ListenAddr, service)
server.Run()
}
Dependency Injection
o Choose a good way to manage package dependency
v Framework (Dig)
v Code Generator (Google-Wire)
Hiring!!!
Sr. Software Engineer – IIOT security
o 2-3
o
o
We are looking for an experienced Software Engineer to develop the
backend management server for an industrial IoT security project.
Golang Pro Tips
References
1. Practical Go: Real world advice for writing maintainable Go programs
https://dave.cheney.net/practical-go/presentations/qcon-china.html
2. GopherCon EU 2018: Peter Bourgon - Best Practices for Industrial Programming
https://www.youtube.com/watch?v=PTE4VJIdHPg
3. What's in a name
https://talks.golang.org/2014/names.slide#1
4. Organize your code with Go packages
https://blog.learngoprogramming.com/code-organization-tips-with-packages-d30de0d11f46
5. Idiomatic Go
https://dmitri.shuralyov.com/idiomatic-go

Más contenido relacionado

La actualidad más candente

#OOP_D_ITS - 3rd - Pointer And References
#OOP_D_ITS - 3rd - Pointer And References#OOP_D_ITS - 3rd - Pointer And References
#OOP_D_ITS - 3rd - Pointer And References
Hadziq Fabroyir
 
Function recap
Function recapFunction recap
Function recap
alish sha
 
Fantom - Programming Language for JVM, CLR, and Javascript
Fantom - Programming Language for JVM, CLR, and JavascriptFantom - Programming Language for JVM, CLR, and Javascript
Fantom - Programming Language for JVM, CLR, and Javascript
Kamil Toman
 

La actualidad más candente (20)

Dynamic Objects,Pointer to function,Array & Pointer,Character String Processing
Dynamic Objects,Pointer to function,Array & Pointer,Character String ProcessingDynamic Objects,Pointer to function,Array & Pointer,Character String Processing
Dynamic Objects,Pointer to function,Array & Pointer,Character String Processing
 
Intro python-object-protocol
Intro python-object-protocolIntro python-object-protocol
Intro python-object-protocol
 
Haskell Jumpstart
Haskell JumpstartHaskell Jumpstart
Haskell Jumpstart
 
This pointer
This pointerThis pointer
This pointer
 
#OOP_D_ITS - 3rd - Pointer And References
#OOP_D_ITS - 3rd - Pointer And References#OOP_D_ITS - 3rd - Pointer And References
#OOP_D_ITS - 3rd - Pointer And References
 
Go serving: Building server app with go
Go serving: Building server app with goGo serving: Building server app with go
Go serving: Building server app with go
 
detailed information about Pointers in c language
detailed information about Pointers in c languagedetailed information about Pointers in c language
detailed information about Pointers in c language
 
Go Lang Tutorial
Go Lang TutorialGo Lang Tutorial
Go Lang Tutorial
 
cpp input & output system basics
cpp input & output system basicscpp input & output system basics
cpp input & output system basics
 
Sol8
Sol8Sol8
Sol8
 
Function recap
Function recapFunction recap
Function recap
 
Fantom - Programming Language for JVM, CLR, and Javascript
Fantom - Programming Language for JVM, CLR, and JavascriptFantom - Programming Language for JVM, CLR, and Javascript
Fantom - Programming Language for JVM, CLR, and Javascript
 
Why my Go program is slow?
Why my Go program is slow?Why my Go program is slow?
Why my Go program is slow?
 
C++ via C#
C++ via C#C++ via C#
C++ via C#
 
Mastering Grammars with PetitParser
Mastering Grammars with PetitParserMastering Grammars with PetitParser
Mastering Grammars with PetitParser
 
FParsec Hands On - F#unctional Londoners 2014
FParsec Hands On -  F#unctional Londoners 2014FParsec Hands On -  F#unctional Londoners 2014
FParsec Hands On - F#unctional Londoners 2014
 
Data structure week 3
Data structure week 3Data structure week 3
Data structure week 3
 
Petitparser at the Deep into Smalltalk School 2011
Petitparser at the Deep into Smalltalk School 2011Petitparser at the Deep into Smalltalk School 2011
Petitparser at the Deep into Smalltalk School 2011
 
GoLightly: A Go Library For Building Virtual Machines
GoLightly: A Go Library For Building Virtual MachinesGoLightly: A Go Library For Building Virtual Machines
GoLightly: A Go Library For Building Virtual Machines
 
Pointers in C
Pointers in CPointers in C
Pointers in C
 

Similar a Maintainable go

Functions And Header Files In C++ | Bjarne stroustrup
Functions And Header Files In C++ | Bjarne stroustrupFunctions And Header Files In C++ | Bjarne stroustrup
Functions And Header Files In C++ | Bjarne stroustrup
SyedHaroonShah4
 
CPP-overviews notes variable data types notes
CPP-overviews notes variable data types notesCPP-overviews notes variable data types notes
CPP-overviews notes variable data types notes
SukhpreetSingh519414
 
cppt-170218053903 (1).pptx
cppt-170218053903 (1).pptxcppt-170218053903 (1).pptx
cppt-170218053903 (1).pptx
WatchDog13
 
Introduction to c programming
Introduction to c programmingIntroduction to c programming
Introduction to c programming
Alpana Gupta
 
Coding standards for java
Coding standards for javaCoding standards for java
Coding standards for java
maheshm1206
 
C programming session 01
C programming session 01C programming session 01
C programming session 01
Dushmanta Nath
 
TI1220 Lecture 14: Domain-Specific Languages
TI1220 Lecture 14: Domain-Specific LanguagesTI1220 Lecture 14: Domain-Specific Languages
TI1220 Lecture 14: Domain-Specific Languages
Eelco Visser
 
Presentation 5th
Presentation 5thPresentation 5th
Presentation 5th
Connex
 

Similar a Maintainable go (20)

C++primer
C++primerC++primer
C++primer
 
Functions And Header Files In C++ | Bjarne stroustrup
Functions And Header Files In C++ | Bjarne stroustrupFunctions And Header Files In C++ | Bjarne stroustrup
Functions And Header Files In C++ | Bjarne stroustrup
 
Getting started with Perl XS and Inline::C
Getting started with Perl XS and Inline::CGetting started with Perl XS and Inline::C
Getting started with Perl XS and Inline::C
 
Go. Why it goes
Go. Why it goesGo. Why it goes
Go. Why it goes
 
CPP-overviews notes variable data types notes
CPP-overviews notes variable data types notesCPP-overviews notes variable data types notes
CPP-overviews notes variable data types notes
 
cppt-170218053903 (1).pptx
cppt-170218053903 (1).pptxcppt-170218053903 (1).pptx
cppt-170218053903 (1).pptx
 
C++ language
C++ languageC++ language
C++ language
 
Summary of C++17 features
Summary of C++17 featuresSummary of C++17 features
Summary of C++17 features
 
Introduction to c programming
Introduction to c programmingIntroduction to c programming
Introduction to c programming
 
Ppt of c vs c#
Ppt of c vs c#Ppt of c vs c#
Ppt of c vs c#
 
Coding standards for java
Coding standards for javaCoding standards for java
Coding standards for java
 
Oops presentation
Oops presentationOops presentation
Oops presentation
 
C programming session 01
C programming session 01C programming session 01
C programming session 01
 
Groovy On Trading Desk (2010)
Groovy On Trading Desk (2010)Groovy On Trading Desk (2010)
Groovy On Trading Desk (2010)
 
TI1220 Lecture 14: Domain-Specific Languages
TI1220 Lecture 14: Domain-Specific LanguagesTI1220 Lecture 14: Domain-Specific Languages
TI1220 Lecture 14: Domain-Specific Languages
 
Csdfsadf
CsdfsadfCsdfsadf
Csdfsadf
 
C
CC
C
 
C
CC
C
 
The GO Language : From Beginners to Gophers
The GO Language : From Beginners to GophersThe GO Language : From Beginners to Gophers
The GO Language : From Beginners to Gophers
 
Presentation 5th
Presentation 5thPresentation 5th
Presentation 5th
 

Último

Hospital management system project report.pdf
Hospital management system project report.pdfHospital management system project report.pdf
Hospital management system project report.pdf
Kamal Acharya
 
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
ssuser89054b
 
"Lesotho Leaps Forward: A Chronicle of Transformative Developments"
"Lesotho Leaps Forward: A Chronicle of Transformative Developments""Lesotho Leaps Forward: A Chronicle of Transformative Developments"
"Lesotho Leaps Forward: A Chronicle of Transformative Developments"
mphochane1998
 
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
AldoGarca30
 

Último (20)

Thermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptThermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.ppt
 
Hospital management system project report.pdf
Hospital management system project report.pdfHospital management system project report.pdf
Hospital management system project report.pdf
 
DC MACHINE-Motoring and generation, Armature circuit equation
DC MACHINE-Motoring and generation, Armature circuit equationDC MACHINE-Motoring and generation, Armature circuit equation
DC MACHINE-Motoring and generation, Armature circuit equation
 
School management system project Report.pdf
School management system project Report.pdfSchool management system project Report.pdf
School management system project Report.pdf
 
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
 
Double Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torqueDouble Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torque
 
Computer Lecture 01.pptxIntroduction to Computers
Computer Lecture 01.pptxIntroduction to ComputersComputer Lecture 01.pptxIntroduction to Computers
Computer Lecture 01.pptxIntroduction to Computers
 
Computer Networks Basics of Network Devices
Computer Networks  Basics of Network DevicesComputer Networks  Basics of Network Devices
Computer Networks Basics of Network Devices
 
"Lesotho Leaps Forward: A Chronicle of Transformative Developments"
"Lesotho Leaps Forward: A Chronicle of Transformative Developments""Lesotho Leaps Forward: A Chronicle of Transformative Developments"
"Lesotho Leaps Forward: A Chronicle of Transformative Developments"
 
Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...
Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...
Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...
 
Design For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the startDesign For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the start
 
GEAR TRAIN- BASIC CONCEPTS AND WORKING PRINCIPLE
GEAR TRAIN- BASIC CONCEPTS AND WORKING PRINCIPLEGEAR TRAIN- BASIC CONCEPTS AND WORKING PRINCIPLE
GEAR TRAIN- BASIC CONCEPTS AND WORKING PRINCIPLE
 
PE 459 LECTURE 2- natural gas basic concepts and properties
PE 459 LECTURE 2- natural gas basic concepts and propertiesPE 459 LECTURE 2- natural gas basic concepts and properties
PE 459 LECTURE 2- natural gas basic concepts and properties
 
A CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptx
A CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptxA CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptx
A CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptx
 
Employee leave management system project.
Employee leave management system project.Employee leave management system project.
Employee leave management system project.
 
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
 
Thermal Engineering Unit - I & II . ppt
Thermal Engineering  Unit - I & II . pptThermal Engineering  Unit - I & II . ppt
Thermal Engineering Unit - I & II . ppt
 
Hostel management system project report..pdf
Hostel management system project report..pdfHostel management system project report..pdf
Hostel management system project report..pdf
 
Work-Permit-Receiver-in-Saudi-Aramco.pptx
Work-Permit-Receiver-in-Saudi-Aramco.pptxWork-Permit-Receiver-in-Saudi-Aramco.pptx
Work-Permit-Receiver-in-Saudi-Aramco.pptx
 
Moment Distribution Method For Btech Civil
Moment Distribution Method For Btech CivilMoment Distribution Method For Btech Civil
Moment Distribution Method For Btech Civil
 

Maintainable go

  • 2. Outline o Naming o Declaration Style o Packages o Design pattern o
  • 4. func startServer(host string, config *Config) func startServer(host string, c *Config) userMap := make(map[string]*User) users := make(map[string]*User) func CountFemale(people []Person) int { c := 0 for i, p := range people { if p.gender == "F" { c++ } } return c } How to make variable names more clear?
  • 5. Short Names o Where the types are descriptive, they should be short. o Where the types are more ambiguous, the names may provide documentation. o The greater the distance between a name's declaration and its uses, the longer the name should be. - Andrew Google Inc. What‘s in a name?
  • 6. Short Names o Single letter for method receivers, loops and branches. o Single words for parameters and local variables. o Two words for methods.
  • 7. Short Names o ‘i' to index o ‘w’ to writer o ‘r’ to reader o ‘b’ to buffer o ‘ok’ check if the key exists in the map
  • 8. Names without their types usersMap := make(map[string]*User) users := make(map[string]*User) Preferred o The name of the variable should describe its contents, not the type of the contents. - Dave Cheney. Practical Go
  • 9. Names Use a consistent naming style A good name is it should be predictable - Dave Cheney. Practical Go
  • 11. Declaration Style var – Declare a variable without initialization := - Declare and initialize a variable var stdnt Student Preferred stdnt := Student{Name: "Cherie"} stdnt := Student{}
  • 12. Declaration Style o nil Slice and non-nil Slice var stdnts []Student Preferred stdnts = make([]Student, 0) // For encoding JSON objects
  • 14. Packages o Do not put all types inside a models folder. o Avoid package names like base, common, or util. Its name doesn’t reflect its purpose, only its function in breaking the import cycle.
  • 15. Packages o Avoid mutable package-global state It is difficult to write unit tests. May cause bugs in complex projects.
  • 16. Packages o Avoid a rigid project structure.
  • 18. API Design o Avoid taking several parameters of the same type. // Example: func Extract(source, target, destination string) error { // Implementation } APIs with multiple parameters of the same type are hard to use correctly. - Dave Cheney
  • 19. API Design o Carefully using nil as parameters. // Bad func DoSomething(cfg *customConfig) { if cfg == nil { // Use default config } } DoSomething(nil)
  • 21. Functional options o A common way to apply your configuration type Configuration struct { Port int Addr string } func NewServer(config *Configuration) { // }
  • 22. Functional options func NewServer(opts ...Option) { cfg := Configuration{ Port: 8080, Addr: "localhost" } // Use option functions to modify your default configuration for _, opt := range opts { opt(&cfg) } } func ChangePort(v int) Option { return func(cfg *Configuration){ cfg.Port = v } } o A better way by using functional options
  • 23. Functional options // Example - gRPC s := grpc.NewServer(grpc.StatsHandler(&ocgrpc.ServerHandler{})) // Example - MongoDB client, err := mongo.NewClient(options.Client().ApplyURI(”.."))
  • 24. Dependency Injection // Example func main() { cfg := GetConfig() db, err := ConnectDatabase(cfg.URN) if err != nil { panic(err) } repo := NewPersonRepository(db) service := NewPersonService(cfg.AccessToken, repo) server := NewServer(cfg.ListenAddr, service) server.Run() }
  • 25. Dependency Injection o Choose a good way to manage package dependency v Framework (Dig) v Code Generator (Google-Wire)
  • 27. Sr. Software Engineer – IIOT security o 2-3 o o We are looking for an experienced Software Engineer to develop the backend management server for an industrial IoT security project.
  • 29. References 1. Practical Go: Real world advice for writing maintainable Go programs https://dave.cheney.net/practical-go/presentations/qcon-china.html 2. GopherCon EU 2018: Peter Bourgon - Best Practices for Industrial Programming https://www.youtube.com/watch?v=PTE4VJIdHPg 3. What's in a name https://talks.golang.org/2014/names.slide#1 4. Organize your code with Go packages https://blog.learngoprogramming.com/code-organization-tips-with-packages-d30de0d11f46 5. Idiomatic Go https://dmitri.shuralyov.com/idiomatic-go