SlideShare una empresa de Scribd logo
1 de 32
Descargar para leer sin conexión
SoftwareEngineeringPrinciples
Softwareengineeringiswhathappenstoprogrammingwhenyouaddtimeand
otherprogrammers.
JaapGroeneveld-jGroeneveld.de
SoftwareEngineeringdealswiththe
challengesof
Communicationbetweenpeople
Communicationovertime
Changingrequirements
Tamingcomplexity
Cleancodeismoreabouthumansthanits
abouttech.
2
Whyinvestincleancode?
Minimizestimespendonreadingandunderstanding
Easiertogrowinthefuture
Lesshuntingforbugs
Easieronboarding.
=>MessycodeisTechnicaldebt.Youwillpayforitdowntheroad.
Messycodehastheuncannyabilitytoslowdownanydeveloperandmakehiswork
muchharder
3
4
BadCodesmells
Rigidity.Thesoftwareisdifficulttochange.Asmallchangecausesacascadeof
subsequentchanges.
Fragility.Thesoftwarebreaksinmanyplacesduetoasinglechange.
Immobility.Youcannotreusepartsofthecodeinotherprojectsbecauseofinvolved
risksandhigheffort.
Opacity.Thecodeishardtounderstand.
NeedlessComplexity.
NeedlessRepetition.
5
6
Principles
Keepitsimple,stupid(KISS)
Youarenʼtgonnaneedit(YAGNI)&PrematureOptimization
Don'trepeatyourself(DRY),singlesourceoftruth.
Don'tconfusesyntacticandsemanticdry-ness
Clearisbetterthanclever.
"Short"doesnotmeaneasytoreadandunderstand.
Avoid"magic"(unobviousbehavior).
Practiceconsistency.
Keepthetestsclean.
Ifyouletthetestsrot,thenyourcodewillrottoo.
Prepareforchange
AlwaysaskhowwillthiscodebehaveifXchanges(butkeepYAGNIinmind) 7
CleanCode-Namingguidelines
Namesareforhumans
Choosedescriptiveandunambiguousnames.
Makemeaningfuldistinction.
Usepronounceablenames.
Usesearchablenames.
Replacemagicnumberswithnamedconstants.
Avoidencodings.Don'tappendprefixesortypeinformation.
8
CleanCode-Namingguidelines
Example
d := 12 // elapsed time in days
// vs
elapsedTimeInDays := 12
9
CleanCode-Explanatoryvariables
func doSomething() {
defer StartTimer()()
// ...
}
// vs
func doSomething() {
stopTimer := StartTimer()
defer stopTimer()
// ...
}
Yesitsonelinemore...
10
CleanCode-Onewordperconcept
Havingaclearterminologyiskeytonotgetconfused.
Itsmoreimportanttobeconsistentthentobeperfect.
Examples?
11
CleanCode-Functionguidelines
Small.
Doone"thing".(SRP-SingleResponsibilityPrinciple)
Usedescriptivenames.
Havenosideeffectsifpossible.
Preferfewerarguments.
Don'tuseflagarguments.Splitmethodintoseveralindependentmethodsthatcanbe
calledfromtheclientwithouttheflag.
12
CleanCode-Commentingguidelines
Onlycommentthewhyandonlyifnotobvious
Alwaystrytoexplainyourselfincode.
Useasexplanationofintent.
Useasclarificationofcode.
Useaswarningofconsequences.
Don'tcommentoutcode.Justremove.
13
StepdownRule
Codeshouldbereadfromtoptobottomlikeanarticle.
Wewanttoreaditasasetof"paragraphs"eachdescribingthecurrentlevelofabstraction
andreferencingdown.
Placefunctionsinthedownwarddirection.
Declarevariablesclosetotheirusage.
Keeplinesshort.
Usewhitespacetoassociaterelatedthingsanddisassociateweaklyrelated.
SeealsoCohesion...
14
Stepdown-Example
package api
func CreatePost(w http.ResponseWriter, r *http.Request) {
post, err := getPostFromRequest(r)
if err != nil {...}
err = validatePost(post)
if err != nil { ... }
err = savePost(post)
if err != nil { ... }
http.WriteHeader(201)
}
func getPostFromRequest(r *http.Request) (Post, error) { ... }
func validatePost(post Post) error { ... }
func savePost(post Post) error { ... }
15
Lineofsight
Alignthehappypathtotheleft;youshould
quicklybeabletoscandownonecolumntosee
theexpectedexecutionflow
see src/lineofsight.go
https://medium.com/@matryer/line-of-sight-in-code-186dd7cdea88 16
Lineofsight
Donʼthidehappypathlogicinsideanestofindentedbraces
Exitearlyfromyourfunction
Avoidelsereturns;considerflippingtheifstatement
Putthehappyreturnstatementastheverylastline
Extractfunctionsandmethodstokeepbodiessmallandreadable
Ifyouneedbigindentedbodies,considergivingthemtheirownfunction
https://medium.com/@matryer/line-of-sight-in-code-186dd7cdea88 17
CleanCode-Dedicatedvaluetypesoverprimitivetype.
func getUserData(userID string) {}
// vs
type UserID string
func getUserData(userID UserID) {}
Impossibleto"accidentally"assignsomethingelse
EasytofindwhereUserIDsareused(searchabilitythroughstaticanalysis)
Preventspositionalproblemsinfunctions
Allowsaddingfunctionstothetype
see typed_primitives.go
18
CleanCode-Avoidimplicitdependency
type Processor struct {
SomeData []string
}
func (p *Processor) Init() {
p.SomeData = []string{"foo", "bar"}
}
func (p *Processor) Step() {
element := p.SomeData[0]
// do something with element
}
Youhavetoknowthatyouhavetocall Init beforecalling Step ,otherwisetheprogram
willcrash.
19
CleanCode-Avoidimplicitdependency
func NewProcessor(someData []string) *Processor {
return &Processor{
SomeData: someData,
}
}
type Processor struct {
SomeData []string
}
func (p *Processor) Step() {
element := p.SomeData[0]
// do something with element
}
See http.Request vs http.NewRequest
20
CleanCode-Avoidimplicitdependency
Anotherexample
func GetFoo(w http.ResponseWriter, r *http.Request) {
dataStore := r.Context().Value("FooDataStore").(FooDataStore)
all := dataStore.All()
_ = json.NewEncoder(w).Encode(all)
}
func main() {
err := http.ListenAndServe(":8080", http.HandlerFunc(GetFoo))
if err != nil {
log.Fatal(err)
}
}
panic:interfaceisnil
21
CleanCode-Avoidimplicitdependency
Basicallyifyouhaveto"know"somethingthatmightbeanimplicitdependency
func GetFoo(dataStore FooDataStore) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
all := dataStore.All()
_ = json.NewEncoder(w).Encode(all)
})
}
func main() {
dataStore = NewFooDataStore()
err := http.ListenAndServe(":8080", GetFoo(dataStore))
if err != nil {
log.Fatal(err)
}
}
Weenforcecorrectusage 22
SOLIDPrinciples
RobertC.Martin
SingleResponsibilityPrinciple
Open-ClosedPrinciple
LiskovSubstitutionPrinciple
InterfaceSegregationPrinciple
DependencyInversionPrinciple
23
SRP/Separationofconcerns
Abstraction,increasemodularity
Lessneedtoknow/workonmultiplepartsofthecode(cognitiveload)
Easiertochangeimplementations
Easiertoisolatebugs
Seealsolayerarchitecture,coupling
24
CouplingvsCohesion
25
CouplingvsCohesion
Couplingreferstotheinterdependenciesbetweenmodules,whilecohesiondescribes
howrelatedthefunctionswithinasinglemoduleare
Highcoupling,lowcohesion=>
Lowcoupling,highcohesion=>
26
27
Highcohesion
SeeStepdownRule
Declarevariablesclosetotheirusage.
Dependentfunctionsshouldbeclose.
Similarfunctionsshouldbeclose(samefileorsamepackage).
SRPishelpful
28
Lowcoupling
DependencyinversionPrinciple
High-levelmodulesshouldnotdependonlow-levelmodules.Bothshoulddepend
onabstractions(e.g.interfaces).
InterfaceSegregationPrinciple
Thebiggertheinterface,theweakertheabstraction
29
DependencyinjectioninGo
Implicitinterfaces
DuckTyping
Avoidcyclicdependencies
30
DependencyinjectioninGo
package cli
type DataStore interface {
GetData() model.Data
}
func Run(dataStore DataStore) {}
package persistence
type FileDataStore struct {}
func (s *FileDataStore) GetData() model.Data
package main
func main() {
dataStore := &persistence.FileDataStore{}
cli.Run(dataStore)
}
31
Literature
Lessonslearntfrom“TheCleanCode”
RottingdesignBINGO!
SixShadesofCoupling
TheforgottenrealmofCohesion
32

Más contenido relacionado

Similar a Jaap Groeneveld - Software Engineering Principles

The Smells Of Bad Design
The Smells Of Bad DesignThe Smells Of Bad Design
The Smells Of Bad Design
guest446c0
 
The Smells Of Bad Design
The Smells Of Bad DesignThe Smells Of Bad Design
The Smells Of Bad Design
James Peckham
 
A taxonomy of obfuscating transformations
A taxonomy of obfuscating transformationsA taxonomy of obfuscating transformations
A taxonomy of obfuscating transformations
emanuele_nl
 
London F-Sharp User Group : Don Syme on F# - 09/09/2010
London F-Sharp User Group : Don Syme on F# - 09/09/2010London F-Sharp User Group : Don Syme on F# - 09/09/2010
London F-Sharp User Group : Don Syme on F# - 09/09/2010
Skills Matter
 

Similar a Jaap Groeneveld - Software Engineering Principles (20)

Jaap Groeneveld - Software Architecture
Jaap Groeneveld - Software ArchitectureJaap Groeneveld - Software Architecture
Jaap Groeneveld - Software Architecture
 
Camunda Chapter Hamburg - Surviving the hyperautomation low code bubble
Camunda Chapter Hamburg - Surviving the hyperautomation low code bubbleCamunda Chapter Hamburg - Surviving the hyperautomation low code bubble
Camunda Chapter Hamburg - Surviving the hyperautomation low code bubble
 
2011.02.18 marco parenzan - case study. conversione di una applicazione for...
2011.02.18   marco parenzan - case study. conversione di una applicazione for...2011.02.18   marco parenzan - case study. conversione di una applicazione for...
2011.02.18 marco parenzan - case study. conversione di una applicazione for...
 
The art of computer programming
The art of computer programmingThe art of computer programming
The art of computer programming
 
The Smells Of Bad Design
The Smells Of Bad DesignThe Smells Of Bad Design
The Smells Of Bad Design
 
The Smells Of Bad Design
The Smells Of Bad DesignThe Smells Of Bad Design
The Smells Of Bad Design
 
Dotfuscator
DotfuscatorDotfuscator
Dotfuscator
 
CraftConf: Surviving the hyperautomation low code bubbl
CraftConf: Surviving the hyperautomation low code bubblCraftConf: Surviving the hyperautomation low code bubbl
CraftConf: Surviving the hyperautomation low code bubbl
 
A taxonomy of obfuscating transformations
A taxonomy of obfuscating transformationsA taxonomy of obfuscating transformations
A taxonomy of obfuscating transformations
 
Resume
ResumeResume
Resume
 
Cr java concept by vikas jagtap
Cr java  concept by vikas jagtapCr java  concept by vikas jagtap
Cr java concept by vikas jagtap
 
Developers survival-guide
Developers survival-guideDevelopers survival-guide
Developers survival-guide
 
Privacy is a UX problem (David Dahl)
Privacy is a UX problem (David Dahl)Privacy is a UX problem (David Dahl)
Privacy is a UX problem (David Dahl)
 
What frameworks can do for you – and what not (IPC14 SE)
What frameworks can do for you – and what not (IPC14 SE)What frameworks can do for you – and what not (IPC14 SE)
What frameworks can do for you – and what not (IPC14 SE)
 
linkedin brainies
linkedin brainieslinkedin brainies
linkedin brainies
 
Structured Software Design
Structured Software DesignStructured Software Design
Structured Software Design
 
London F-Sharp User Group : Don Syme on F# - 09/09/2010
London F-Sharp User Group : Don Syme on F# - 09/09/2010London F-Sharp User Group : Don Syme on F# - 09/09/2010
London F-Sharp User Group : Don Syme on F# - 09/09/2010
 
Sunny Tech 2019 - Craft Forever
Sunny Tech 2019 - Craft ForeverSunny Tech 2019 - Craft Forever
Sunny Tech 2019 - Craft Forever
 
A Gentle introduction to microservices
A Gentle introduction to microservicesA Gentle introduction to microservices
A Gentle introduction to microservices
 
Androides y Mazmorras. Part I (dungeons & robots)
Androides y Mazmorras. Part I (dungeons & robots)Androides y Mazmorras. Part I (dungeons & robots)
Androides y Mazmorras. Part I (dungeons & robots)
 

Último

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

Último (20)

The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 

Jaap Groeneveld - Software Engineering Principles