SlideShare a Scribd company logo
AN EXERCISE IN CLEANER CODE
FROM LEGACY TO MAINTAINABLE
Gavin Pickin
cf.Objective() 2017
Who am I?
Gavin Pickin – developing Web Apps since late 90s
● Software Consultant for Ortus Solutions
● ContentBox Evangelist
What else do you need to know?
● Blog - http://www.gpickin.com
● Twitter – http://twitter.com/gpickin
● Github - https://github.com/gpickin
Let’s get on with the show.
Agenda
● What is clean code?
● Lowering Cognitive Load
● General Rules of Clean Code
● Naming, Functions, Comments
● Source Code, Formatting
● Let’s look at some code
What is Clean Code
Not everyone can agree on what clean code is… but
often people reference Uncle Bob’s book.
Robert C. Martin stated in his book Clean Code: A
Handbook of Agile Software Craftsmanship, “Clean
code is code that has been taken care of. Someone
has taken the time to keep it simple and orderly. They
have paid appropriate attention to details. They have
cared.”
Simply, it is a quest for code that is easy to
understand and easy to maintain.
"Any fool can write code that a
computer can understand.
Good programmers write code that
humans can understand."
- Martin Fowler
Lower the Cognitive Load
In cognitive psychology, cognitive load refers to the total amount of mental effort
being used in the working memory. Cognitive load theory was developed out of
the study of problem solving by John Sweller in the late 1980s
Wikipedia: https://en.wikipedia.org/wiki/Cognitive_load
Lower the Cognitive Load
When reading code, make it easier on yourself:
● Abstract complexity
● Single responsibility
● Short, sweet and to the point
● Be Consistent
● Explanatory Variables and Function Names
● Structure your Code to help readability
● Use Coding Conventions
Don’t suffocate your code, let it breathe
● When reading code, white space can be your friend.
● Let whitespace separate code that should be separated
● Let the lack of whitespace help you decide what code is connected.
General Rules of Clean Code
● Remember, you write code one time, while the same code might be read
hundreds of times… code for the primary use case… make it readable.
● Decide on conventions, and stick to them.
● Coding by yourself overtime isn’t easy, in a team, it can be a nightmare.
● KISS - Keep it Simple Stupid
● Boy Scout Rules - Leave it cleaner than you found it
● Look past the symptom, find the root problem or cause.
Naming Rules
There is a saying, that there are 2 really hard things in software engineering
● Cache Invalidation
● Naming things
● And 1 off errors
They were right, naming things is really hard.
Let’s look at some rules to help with Naming
Naming Rules
● Choose descriptive and unambiguous names.
● Make names meaningful and distinct.
● Use pronounceable names.
● Use searchable names.
● Replace magic numbers with named constants.
● Try to avoid encodings and prefixes or type information
● Don’t use Acronyms unless they are universal like URL.
Naming - Meaningful distinct name
-- Do This --
customerAddress = getCustomerAddress()
dangerColor = ‘##FF0000’
-- Not this --
Ca = CustAddDetails()
redColor = “##FF0000”
Naming - Constants
They should all be in uppercase separated by underscores "_". Examples:
-- DO THIS --
INTERCEPTOR_POINTS = "";
LINE_SEP = "-";
MAX = "123";
-- NOT THIS --
interceptor-points = "";
line_sep = "d";
max = "123";
Naming - Acronyms and Abbreviations
-- DO THIS --
URLScanner.cfc
parseHTTPString()
-- NOT THIS --
url-scanner.cfc
UrlScanner.cfc
parseHttpString()
ParseHttpString()
Naming - avoid prefixes suffixes
-- Do This --
dayOfWeek = “thursday”
aUsers = getUsers( { active = true } );
-- Not this --
strDow = “thursday”
User-array = getUsers( { active = true } );
Functions
● Keep the function Short and Sweet
● Single responsibility - do one thing
● Functions have names, use the same rules for naming functions
● Try not to have too many arguments - use structs for more options.
● Keep side effects to a minimum
● Don’t use Flag arguments
○ Use separate methods that can be called from the client
● Use functions to hide complexity, to keep other functions short, sweet, and
easier to understand
Functions - Too many arguments
--Do this --
searchCars( { seats=4, minPrice = 20,000 } )
-- Not this --
searchCars( seats, color, maxPrice, minPrice, type, make )
Functions - Avoid Side Effects
https://github.com/ryanmcdermott/clean-code-javascript#avoid-side-effects-part-1
Functions - Don’t use Flags - Bad
function createFile(name, temp) {
if (temp) {
fs.create(`./temp/${name}`);
} else {
fs.create(name);
}
}
Functions - Don’t use Flags - Good
function createFile(name) {
fs.create(name);
}
function createTempFile(name) {
createFile(`./temp/${name}`);
}
Comments
● Try and let code speak for you where possible
● Comments should add value and meaning to the code
● Don’t add a comment that is redundant - ie save user
● Don’t add comments just to add them, add value
● Add comments in advance, not on closing braces
● Don’t comment out code, remove it, that’s what Git is for
● Explain the intent, not the actual implementation
● Useful when explaining consequences or ramifications
● ColdDoc will generate docs from javadoc styled comments
○ https://github.com/Ortus-Solutions/commandbox/blob/development/src/cfml/system/BaseCom
mand.cfc
○ http://apidocs.ortussolutions.com/commandbox/3.7.0/index.html
Structuring your Source Code
● Separate your Code Concepts vertically in your Files
● Variables should be declared close to where they are being used
○ This has changed from the old days, where top of the function was the preference. Although,
which a short function, top should be close ;)
● Functions that are Dependant should be close to each other
● Similar functions should be close to each other
● Use indention consistently
Formatting
● Everyone in the team should use the same conventions
● If the language has conventions, use that
○ CFML doesn’t, that’s why Ortus has made theirs public.
https://github.com/Ortus-Solutions/coding-standards
● Keep Lines short
● Don’t modify a file just to format it… if you are adding to the file, then
format it
Resources
Ortus Conventions:
https://github.com/Ortus-Solutions/coding-standards
Uncle Bob’s Clean Code on Amazon:
http://amzn.to/2tfKL9C
Javascript Clean Code:
https://github.com/ryanmcdermott/clean-code-javascript
Clean Code course on Pluralsight:
https://www.pluralsight.com/courses/writing-clean-code-humans
Too much text
Not enough code?
Lets try a live example - live code
- we’re living dangerously
https://github.com/elpete/cb-module-
template/blob/master/commands/mo
dule/scaffold.cfc
AN EXERCISE IN CLEANER CODE - FROM LEGACY TO MAINTAINABLE
AN EXERCISE IN CLEANER CODE - FROM LEGACY TO MAINTAINABLE

More Related Content

What's hot

API-first development
API-first developmentAPI-first development
API-first developmentVasco Veloso
 
Tools and techniques for APIs
Tools and techniques for APIsTools and techniques for APIs
Tools and techniques for APIsJason Harmon
 
Tools for designing and building great APIs
Tools for designing and building great APIsTools for designing and building great APIs
Tools for designing and building great APIsKong Inc.
 
API First Workflow: How could we have better API Docs through DevOps pipeline
API First Workflow: How could we have better API Docs through DevOps pipelineAPI First Workflow: How could we have better API Docs through DevOps pipeline
API First Workflow: How could we have better API Docs through DevOps pipelinePronovix
 
apidays LIVE Helsinki - Implementing OpenAPI and GraphQL Services with gRPC b...
apidays LIVE Helsinki - Implementing OpenAPI and GraphQL Services with gRPC b...apidays LIVE Helsinki - Implementing OpenAPI and GraphQL Services with gRPC b...
apidays LIVE Helsinki - Implementing OpenAPI and GraphQL Services with gRPC b...apidays
 
APIdays Paris 2019 - API Descriptions as Product Code by Phil Sturgeon, Stopl...
APIdays Paris 2019 - API Descriptions as Product Code by Phil Sturgeon, Stopl...APIdays Paris 2019 - API Descriptions as Product Code by Phil Sturgeon, Stopl...
APIdays Paris 2019 - API Descriptions as Product Code by Phil Sturgeon, Stopl...apidays
 
Why your APIs should fly first class
Why your APIs should fly first classWhy your APIs should fly first class
Why your APIs should fly first classLibbySchulze
 
apidays LIVE Paris 2021 - Localizing OpenAPI Specification by Olga Baybakova,...
apidays LIVE Paris 2021 - Localizing OpenAPI Specification by Olga Baybakova,...apidays LIVE Paris 2021 - Localizing OpenAPI Specification by Olga Baybakova,...
apidays LIVE Paris 2021 - Localizing OpenAPI Specification by Olga Baybakova,...apidays
 
Designing APIs with OpenAPI Spec
Designing APIs with OpenAPI SpecDesigning APIs with OpenAPI Spec
Designing APIs with OpenAPI SpecAdam Paxton
 
apidays LIVE London 2021 - Consumer-first APIs in Open Banking by Chris Dudle...
apidays LIVE London 2021 - Consumer-first APIs in Open Banking by Chris Dudle...apidays LIVE London 2021 - Consumer-first APIs in Open Banking by Chris Dudle...
apidays LIVE London 2021 - Consumer-first APIs in Open Banking by Chris Dudle...apidays
 
apidays LIVE Australia 2020 - Productising your Microservices as API Products...
apidays LIVE Australia 2020 - Productising your Microservices as API Products...apidays LIVE Australia 2020 - Productising your Microservices as API Products...
apidays LIVE Australia 2020 - Productising your Microservices as API Products...apidays
 
Scaling Your Team With GraphQL: Why Relationships Matter
Scaling Your Team With GraphQL: Why Relationships MatterScaling Your Team With GraphQL: Why Relationships Matter
Scaling Your Team With GraphQL: Why Relationships MatterJoel Bowen
 
apidays LIVE Hong Kong 2021 - Less Data is More by Damir Svrtan, Netflix
apidays LIVE Hong Kong 2021 - Less Data is More by Damir Svrtan, Netflixapidays LIVE Hong Kong 2021 - Less Data is More by Damir Svrtan, Netflix
apidays LIVE Hong Kong 2021 - Less Data is More by Damir Svrtan, Netflixapidays
 
Building APIs with Node.js and Swagger
Building APIs with Node.js and SwaggerBuilding APIs with Node.js and Swagger
Building APIs with Node.js and SwaggerJeremy Whitlock
 
Swagger for-your-api
Swagger for-your-apiSwagger for-your-api
Swagger for-your-apiTony Tam
 
TRAX technical highlights
TRAX technical highlightsTRAX technical highlights
TRAX technical highlightsESUG
 
Automating the API Product Lifecycle
Automating the API Product LifecycleAutomating the API Product Lifecycle
Automating the API Product LifecyclePronovix
 
Open Event API
Open Event APIOpen Event API
Open Event APIAvi Aryan
 
apidays LIVE Paris 2021 - Using OpenAPI to configure your API Gateway by Ole ...
apidays LIVE Paris 2021 - Using OpenAPI to configure your API Gateway by Ole ...apidays LIVE Paris 2021 - Using OpenAPI to configure your API Gateway by Ole ...
apidays LIVE Paris 2021 - Using OpenAPI to configure your API Gateway by Ole ...apidays
 

What's hot (20)

API-first development
API-first developmentAPI-first development
API-first development
 
Tools and techniques for APIs
Tools and techniques for APIsTools and techniques for APIs
Tools and techniques for APIs
 
Tools for designing and building great APIs
Tools for designing and building great APIsTools for designing and building great APIs
Tools for designing and building great APIs
 
API First Workflow: How could we have better API Docs through DevOps pipeline
API First Workflow: How could we have better API Docs through DevOps pipelineAPI First Workflow: How could we have better API Docs through DevOps pipeline
API First Workflow: How could we have better API Docs through DevOps pipeline
 
apidays LIVE Helsinki - Implementing OpenAPI and GraphQL Services with gRPC b...
apidays LIVE Helsinki - Implementing OpenAPI and GraphQL Services with gRPC b...apidays LIVE Helsinki - Implementing OpenAPI and GraphQL Services with gRPC b...
apidays LIVE Helsinki - Implementing OpenAPI and GraphQL Services with gRPC b...
 
APIdays Paris 2019 - API Descriptions as Product Code by Phil Sturgeon, Stopl...
APIdays Paris 2019 - API Descriptions as Product Code by Phil Sturgeon, Stopl...APIdays Paris 2019 - API Descriptions as Product Code by Phil Sturgeon, Stopl...
APIdays Paris 2019 - API Descriptions as Product Code by Phil Sturgeon, Stopl...
 
Why your APIs should fly first class
Why your APIs should fly first classWhy your APIs should fly first class
Why your APIs should fly first class
 
apidays LIVE Paris 2021 - Localizing OpenAPI Specification by Olga Baybakova,...
apidays LIVE Paris 2021 - Localizing OpenAPI Specification by Olga Baybakova,...apidays LIVE Paris 2021 - Localizing OpenAPI Specification by Olga Baybakova,...
apidays LIVE Paris 2021 - Localizing OpenAPI Specification by Olga Baybakova,...
 
Designing APIs with OpenAPI Spec
Designing APIs with OpenAPI SpecDesigning APIs with OpenAPI Spec
Designing APIs with OpenAPI Spec
 
Api guide
Api guide Api guide
Api guide
 
apidays LIVE London 2021 - Consumer-first APIs in Open Banking by Chris Dudle...
apidays LIVE London 2021 - Consumer-first APIs in Open Banking by Chris Dudle...apidays LIVE London 2021 - Consumer-first APIs in Open Banking by Chris Dudle...
apidays LIVE London 2021 - Consumer-first APIs in Open Banking by Chris Dudle...
 
apidays LIVE Australia 2020 - Productising your Microservices as API Products...
apidays LIVE Australia 2020 - Productising your Microservices as API Products...apidays LIVE Australia 2020 - Productising your Microservices as API Products...
apidays LIVE Australia 2020 - Productising your Microservices as API Products...
 
Scaling Your Team With GraphQL: Why Relationships Matter
Scaling Your Team With GraphQL: Why Relationships MatterScaling Your Team With GraphQL: Why Relationships Matter
Scaling Your Team With GraphQL: Why Relationships Matter
 
apidays LIVE Hong Kong 2021 - Less Data is More by Damir Svrtan, Netflix
apidays LIVE Hong Kong 2021 - Less Data is More by Damir Svrtan, Netflixapidays LIVE Hong Kong 2021 - Less Data is More by Damir Svrtan, Netflix
apidays LIVE Hong Kong 2021 - Less Data is More by Damir Svrtan, Netflix
 
Building APIs with Node.js and Swagger
Building APIs with Node.js and SwaggerBuilding APIs with Node.js and Swagger
Building APIs with Node.js and Swagger
 
Swagger for-your-api
Swagger for-your-apiSwagger for-your-api
Swagger for-your-api
 
TRAX technical highlights
TRAX technical highlightsTRAX technical highlights
TRAX technical highlights
 
Automating the API Product Lifecycle
Automating the API Product LifecycleAutomating the API Product Lifecycle
Automating the API Product Lifecycle
 
Open Event API
Open Event APIOpen Event API
Open Event API
 
apidays LIVE Paris 2021 - Using OpenAPI to configure your API Gateway by Ole ...
apidays LIVE Paris 2021 - Using OpenAPI to configure your API Gateway by Ole ...apidays LIVE Paris 2021 - Using OpenAPI to configure your API Gateway by Ole ...
apidays LIVE Paris 2021 - Using OpenAPI to configure your API Gateway by Ole ...
 

Similar to AN EXERCISE IN CLEANER CODE - FROM LEGACY TO MAINTAINABLE

Javascript Programming according to Industry Standards.pptx
Javascript Programming according to Industry Standards.pptxJavascript Programming according to Industry Standards.pptx
Javascript Programming according to Industry Standards.pptxMukundSonaiya1
 
Writing Readable Code
Writing Readable CodeWriting Readable Code
Writing Readable Codeeddiehaber
 
Taming the Legacy Beast: Turning wild old code into a sleak new thoroughbread.
Taming the Legacy Beast: Turning wild old code into a sleak new thoroughbread.Taming the Legacy Beast: Turning wild old code into a sleak new thoroughbread.
Taming the Legacy Beast: Turning wild old code into a sleak new thoroughbread.Chris Laning
 
Keep your repo clean
Keep your repo cleanKeep your repo clean
Keep your repo cleanHector Canto
 
Writing clean scientific software Murphy cleancoding
Writing clean scientific software Murphy cleancodingWriting clean scientific software Murphy cleancoding
Writing clean scientific software Murphy cleancodingsaber tabatabaee
 
Software Craftmanship - Cours Polytech
Software Craftmanship - Cours PolytechSoftware Craftmanship - Cours Polytech
Software Craftmanship - Cours Polytechyannick grenzinger
 
Software development best practices & coding guidelines
Software development best practices & coding guidelinesSoftware development best practices & coding guidelines
Software development best practices & coding guidelinesAnkur Goyal
 
How to write good quality code
How to write good quality codeHow to write good quality code
How to write good quality codeHayden Bleasel
 
YAGNI Principle and Clean Code
YAGNI Principle and Clean CodeYAGNI Principle and Clean Code
YAGNI Principle and Clean CodeLuan Reffatti
 
Half-automatic Compilable Source Code Recovery
Half-automatic Compilable Source Code RecoveryHalf-automatic Compilable Source Code Recovery
Half-automatic Compilable Source Code RecoveryJoxean Koret
 
Not Your Fathers C - C Application Development In 2016
Not Your Fathers C - C Application Development In 2016Not Your Fathers C - C Application Development In 2016
Not Your Fathers C - C Application Development In 2016maiktoepfer
 
How I Learned to Stop Worrying and Love Legacy Code.....
How I Learned to Stop Worrying and Love Legacy Code.....How I Learned to Stop Worrying and Love Legacy Code.....
How I Learned to Stop Worrying and Love Legacy Code.....Mike Harris
 
Clean code, Feb 2012
Clean code, Feb 2012Clean code, Feb 2012
Clean code, Feb 2012cobyst
 
WordCamp Nashville: Clean Code for WordPress
WordCamp Nashville: Clean Code for WordPressWordCamp Nashville: Clean Code for WordPress
WordCamp Nashville: Clean Code for WordPressmtoppa
 
The View - Lotusscript coding best practices
The View - Lotusscript coding best practicesThe View - Lotusscript coding best practices
The View - Lotusscript coding best practicesBill Buchan
 

Similar to AN EXERCISE IN CLEANER CODE - FROM LEGACY TO MAINTAINABLE (20)

Javascript Programming according to Industry Standards.pptx
Javascript Programming according to Industry Standards.pptxJavascript Programming according to Industry Standards.pptx
Javascript Programming according to Industry Standards.pptx
 
Writing Readable Code
Writing Readable CodeWriting Readable Code
Writing Readable Code
 
Taming the Legacy Beast: Turning wild old code into a sleak new thoroughbread.
Taming the Legacy Beast: Turning wild old code into a sleak new thoroughbread.Taming the Legacy Beast: Turning wild old code into a sleak new thoroughbread.
Taming the Legacy Beast: Turning wild old code into a sleak new thoroughbread.
 
Keep your repo clean
Keep your repo cleanKeep your repo clean
Keep your repo clean
 
Writing clean scientific software Murphy cleancoding
Writing clean scientific software Murphy cleancodingWriting clean scientific software Murphy cleancoding
Writing clean scientific software Murphy cleancoding
 
Software Craftmanship - Cours Polytech
Software Craftmanship - Cours PolytechSoftware Craftmanship - Cours Polytech
Software Craftmanship - Cours Polytech
 
Good Coding Practices with JavaScript
Good Coding Practices with JavaScriptGood Coding Practices with JavaScript
Good Coding Practices with JavaScript
 
Software development best practices & coding guidelines
Software development best practices & coding guidelinesSoftware development best practices & coding guidelines
Software development best practices & coding guidelines
 
How to write good quality code
How to write good quality codeHow to write good quality code
How to write good quality code
 
YAGNI Principle and Clean Code
YAGNI Principle and Clean CodeYAGNI Principle and Clean Code
YAGNI Principle and Clean Code
 
engage 2014 - JavaBlast
engage 2014 - JavaBlastengage 2014 - JavaBlast
engage 2014 - JavaBlast
 
Half-automatic Compilable Source Code Recovery
Half-automatic Compilable Source Code RecoveryHalf-automatic Compilable Source Code Recovery
Half-automatic Compilable Source Code Recovery
 
DDD with Behat
DDD with BehatDDD with Behat
DDD with Behat
 
Not Your Fathers C - C Application Development In 2016
Not Your Fathers C - C Application Development In 2016Not Your Fathers C - C Application Development In 2016
Not Your Fathers C - C Application Development In 2016
 
How I Learned to Stop Worrying and Love Legacy Code.....
How I Learned to Stop Worrying and Love Legacy Code.....How I Learned to Stop Worrying and Love Legacy Code.....
How I Learned to Stop Worrying and Love Legacy Code.....
 
Clean code, Feb 2012
Clean code, Feb 2012Clean code, Feb 2012
Clean code, Feb 2012
 
Code Review
Code ReviewCode Review
Code Review
 
Clean code and code smells
Clean code and code smellsClean code and code smells
Clean code and code smells
 
WordCamp Nashville: Clean Code for WordPress
WordCamp Nashville: Clean Code for WordPressWordCamp Nashville: Clean Code for WordPress
WordCamp Nashville: Clean Code for WordPress
 
The View - Lotusscript coding best practices
The View - Lotusscript coding best practicesThe View - Lotusscript coding best practices
The View - Lotusscript coding best practices
 

More from Gavin Pickin

Itb 2021 - Bulding Quick APIs by Gavin Pickin
Itb 2021 - Bulding Quick APIs by Gavin PickinItb 2021 - Bulding Quick APIs by Gavin Pickin
Itb 2021 - Bulding Quick APIs by Gavin PickinGavin Pickin
 
Containerizing ContentBox CMS
Containerizing ContentBox CMSContainerizing ContentBox CMS
Containerizing ContentBox CMSGavin Pickin
 
ColdBox APIs + VueJS - powering Mobile, Desktop and Web Apps with 1 VueJS cod...
ColdBox APIs + VueJS - powering Mobile, Desktop and Web Apps with 1 VueJS cod...ColdBox APIs + VueJS - powering Mobile, Desktop and Web Apps with 1 VueJS cod...
ColdBox APIs + VueJS - powering Mobile, Desktop and Web Apps with 1 VueJS cod...Gavin Pickin
 
3 WAYS TO TEST YOUR COLDFUSION API
3 WAYS TO TEST YOUR COLDFUSION API3 WAYS TO TEST YOUR COLDFUSION API
3 WAYS TO TEST YOUR COLDFUSION APIGavin Pickin
 
Take home your very own free Vagrant CFML Dev Environment - Presented at dev....
Take home your very own free Vagrant CFML Dev Environment - Presented at dev....Take home your very own free Vagrant CFML Dev Environment - Presented at dev....
Take home your very own free Vagrant CFML Dev Environment - Presented at dev....Gavin Pickin
 
How do I write Testable Javascript - Presented at dev.Objective() June 16, 2016
How do I write Testable Javascript - Presented at dev.Objective() June 16, 2016How do I write Testable Javascript - Presented at dev.Objective() June 16, 2016
How do I write Testable Javascript - Presented at dev.Objective() June 16, 2016Gavin Pickin
 
BDD Testing and Automating from the trenches - Presented at Into The Box June...
BDD Testing and Automating from the trenches - Presented at Into The Box June...BDD Testing and Automating from the trenches - Presented at Into The Box June...
BDD Testing and Automating from the trenches - Presented at Into The Box June...Gavin Pickin
 
How do I write Testable Javascript so I can Test my CF API on Server and Client
How do I write Testable Javascript so I can Test my CF API on Server and ClientHow do I write Testable Javascript so I can Test my CF API on Server and Client
How do I write Testable Javascript so I can Test my CF API on Server and ClientGavin Pickin
 
Just Mock It - Mocks and Stubs
Just Mock It - Mocks and StubsJust Mock It - Mocks and Stubs
Just Mock It - Mocks and StubsGavin Pickin
 
How do I write Testable Javascript?
How do I write Testable Javascript?How do I write Testable Javascript?
How do I write Testable Javascript?Gavin Pickin
 
Getting your Hooks into Cordova
Getting your Hooks into CordovaGetting your Hooks into Cordova
Getting your Hooks into CordovaGavin Pickin
 
Setting up your Multi Engine Environment - Apache Railo and ColdFusion
Setting up your Multi Engine Environment - Apache Railo and ColdFusionSetting up your Multi Engine Environment - Apache Railo and ColdFusion
Setting up your Multi Engine Environment - Apache Railo and ColdFusionGavin Pickin
 

More from Gavin Pickin (12)

Itb 2021 - Bulding Quick APIs by Gavin Pickin
Itb 2021 - Bulding Quick APIs by Gavin PickinItb 2021 - Bulding Quick APIs by Gavin Pickin
Itb 2021 - Bulding Quick APIs by Gavin Pickin
 
Containerizing ContentBox CMS
Containerizing ContentBox CMSContainerizing ContentBox CMS
Containerizing ContentBox CMS
 
ColdBox APIs + VueJS - powering Mobile, Desktop and Web Apps with 1 VueJS cod...
ColdBox APIs + VueJS - powering Mobile, Desktop and Web Apps with 1 VueJS cod...ColdBox APIs + VueJS - powering Mobile, Desktop and Web Apps with 1 VueJS cod...
ColdBox APIs + VueJS - powering Mobile, Desktop and Web Apps with 1 VueJS cod...
 
3 WAYS TO TEST YOUR COLDFUSION API
3 WAYS TO TEST YOUR COLDFUSION API3 WAYS TO TEST YOUR COLDFUSION API
3 WAYS TO TEST YOUR COLDFUSION API
 
Take home your very own free Vagrant CFML Dev Environment - Presented at dev....
Take home your very own free Vagrant CFML Dev Environment - Presented at dev....Take home your very own free Vagrant CFML Dev Environment - Presented at dev....
Take home your very own free Vagrant CFML Dev Environment - Presented at dev....
 
How do I write Testable Javascript - Presented at dev.Objective() June 16, 2016
How do I write Testable Javascript - Presented at dev.Objective() June 16, 2016How do I write Testable Javascript - Presented at dev.Objective() June 16, 2016
How do I write Testable Javascript - Presented at dev.Objective() June 16, 2016
 
BDD Testing and Automating from the trenches - Presented at Into The Box June...
BDD Testing and Automating from the trenches - Presented at Into The Box June...BDD Testing and Automating from the trenches - Presented at Into The Box June...
BDD Testing and Automating from the trenches - Presented at Into The Box June...
 
How do I write Testable Javascript so I can Test my CF API on Server and Client
How do I write Testable Javascript so I can Test my CF API on Server and ClientHow do I write Testable Javascript so I can Test my CF API on Server and Client
How do I write Testable Javascript so I can Test my CF API on Server and Client
 
Just Mock It - Mocks and Stubs
Just Mock It - Mocks and StubsJust Mock It - Mocks and Stubs
Just Mock It - Mocks and Stubs
 
How do I write Testable Javascript?
How do I write Testable Javascript?How do I write Testable Javascript?
How do I write Testable Javascript?
 
Getting your Hooks into Cordova
Getting your Hooks into CordovaGetting your Hooks into Cordova
Getting your Hooks into Cordova
 
Setting up your Multi Engine Environment - Apache Railo and ColdFusion
Setting up your Multi Engine Environment - Apache Railo and ColdFusionSetting up your Multi Engine Environment - Apache Railo and ColdFusion
Setting up your Multi Engine Environment - Apache Railo and ColdFusion
 

Recently uploaded

Article writing on excessive use of internet.pptx
Article writing on excessive use of internet.pptxArticle writing on excessive use of internet.pptx
Article writing on excessive use of internet.pptxabhinandnam9997
 
一比一原版UTS毕业证悉尼科技大学毕业证成绩单如何办理
一比一原版UTS毕业证悉尼科技大学毕业证成绩单如何办理一比一原版UTS毕业证悉尼科技大学毕业证成绩单如何办理
一比一原版UTS毕业证悉尼科技大学毕业证成绩单如何办理aagad
 
The AI Powered Organization-Intro to AI-LAN.pdf
The AI Powered Organization-Intro to AI-LAN.pdfThe AI Powered Organization-Intro to AI-LAN.pdf
The AI Powered Organization-Intro to AI-LAN.pdfSiskaFitrianingrum
 
The+Prospects+of+E-Commerce+in+China.pptx
The+Prospects+of+E-Commerce+in+China.pptxThe+Prospects+of+E-Commerce+in+China.pptx
The+Prospects+of+E-Commerce+in+China.pptxlaozhuseo02
 
How to Use Contact Form 7 Like a Pro.pptx
How to Use Contact Form 7 Like a Pro.pptxHow to Use Contact Form 7 Like a Pro.pptx
How to Use Contact Form 7 Like a Pro.pptxGal Baras
 
The Use of AI in Indonesia Election 2024: A Case Study
The Use of AI in Indonesia Election 2024: A Case StudyThe Use of AI in Indonesia Election 2024: A Case Study
The Use of AI in Indonesia Election 2024: A Case StudyDamar Juniarto
 
ER(Entity Relationship) Diagram for online shopping - TAE
ER(Entity Relationship) Diagram for online shopping - TAEER(Entity Relationship) Diagram for online shopping - TAE
ER(Entity Relationship) Diagram for online shopping - TAEHimani415946
 
History+of+E-commerce+Development+in+China-www.cfye-commerce.shop
History+of+E-commerce+Development+in+China-www.cfye-commerce.shopHistory+of+E-commerce+Development+in+China-www.cfye-commerce.shop
History+of+E-commerce+Development+in+China-www.cfye-commerce.shoplaozhuseo02
 
Multi-cluster Kubernetes Networking- Patterns, Projects and Guidelines
Multi-cluster Kubernetes Networking- Patterns, Projects and GuidelinesMulti-cluster Kubernetes Networking- Patterns, Projects and Guidelines
Multi-cluster Kubernetes Networking- Patterns, Projects and GuidelinesSanjeev Rampal
 
1.Wireless Communication System_Wireless communication is a broad term that i...
1.Wireless Communication System_Wireless communication is a broad term that i...1.Wireless Communication System_Wireless communication is a broad term that i...
1.Wireless Communication System_Wireless communication is a broad term that i...JeyaPerumal1
 

Recently uploaded (12)

Article writing on excessive use of internet.pptx
Article writing on excessive use of internet.pptxArticle writing on excessive use of internet.pptx
Article writing on excessive use of internet.pptx
 
一比一原版UTS毕业证悉尼科技大学毕业证成绩单如何办理
一比一原版UTS毕业证悉尼科技大学毕业证成绩单如何办理一比一原版UTS毕业证悉尼科技大学毕业证成绩单如何办理
一比一原版UTS毕业证悉尼科技大学毕业证成绩单如何办理
 
The AI Powered Organization-Intro to AI-LAN.pdf
The AI Powered Organization-Intro to AI-LAN.pdfThe AI Powered Organization-Intro to AI-LAN.pdf
The AI Powered Organization-Intro to AI-LAN.pdf
 
The+Prospects+of+E-Commerce+in+China.pptx
The+Prospects+of+E-Commerce+in+China.pptxThe+Prospects+of+E-Commerce+in+China.pptx
The+Prospects+of+E-Commerce+in+China.pptx
 
How to Use Contact Form 7 Like a Pro.pptx
How to Use Contact Form 7 Like a Pro.pptxHow to Use Contact Form 7 Like a Pro.pptx
How to Use Contact Form 7 Like a Pro.pptx
 
The Best AI Powered Software - Intellivid AI Studio
The Best AI Powered Software - Intellivid AI StudioThe Best AI Powered Software - Intellivid AI Studio
The Best AI Powered Software - Intellivid AI Studio
 
The Use of AI in Indonesia Election 2024: A Case Study
The Use of AI in Indonesia Election 2024: A Case StudyThe Use of AI in Indonesia Election 2024: A Case Study
The Use of AI in Indonesia Election 2024: A Case Study
 
Stay Ahead with 2024's Top Web Design Trends
Stay Ahead with 2024's Top Web Design TrendsStay Ahead with 2024's Top Web Design Trends
Stay Ahead with 2024's Top Web Design Trends
 
ER(Entity Relationship) Diagram for online shopping - TAE
ER(Entity Relationship) Diagram for online shopping - TAEER(Entity Relationship) Diagram for online shopping - TAE
ER(Entity Relationship) Diagram for online shopping - TAE
 
History+of+E-commerce+Development+in+China-www.cfye-commerce.shop
History+of+E-commerce+Development+in+China-www.cfye-commerce.shopHistory+of+E-commerce+Development+in+China-www.cfye-commerce.shop
History+of+E-commerce+Development+in+China-www.cfye-commerce.shop
 
Multi-cluster Kubernetes Networking- Patterns, Projects and Guidelines
Multi-cluster Kubernetes Networking- Patterns, Projects and GuidelinesMulti-cluster Kubernetes Networking- Patterns, Projects and Guidelines
Multi-cluster Kubernetes Networking- Patterns, Projects and Guidelines
 
1.Wireless Communication System_Wireless communication is a broad term that i...
1.Wireless Communication System_Wireless communication is a broad term that i...1.Wireless Communication System_Wireless communication is a broad term that i...
1.Wireless Communication System_Wireless communication is a broad term that i...
 

AN EXERCISE IN CLEANER CODE - FROM LEGACY TO MAINTAINABLE

  • 1. AN EXERCISE IN CLEANER CODE FROM LEGACY TO MAINTAINABLE Gavin Pickin cf.Objective() 2017
  • 2. Who am I? Gavin Pickin – developing Web Apps since late 90s ● Software Consultant for Ortus Solutions ● ContentBox Evangelist What else do you need to know? ● Blog - http://www.gpickin.com ● Twitter – http://twitter.com/gpickin ● Github - https://github.com/gpickin Let’s get on with the show.
  • 3. Agenda ● What is clean code? ● Lowering Cognitive Load ● General Rules of Clean Code ● Naming, Functions, Comments ● Source Code, Formatting ● Let’s look at some code
  • 4. What is Clean Code Not everyone can agree on what clean code is… but often people reference Uncle Bob’s book. Robert C. Martin stated in his book Clean Code: A Handbook of Agile Software Craftsmanship, “Clean code is code that has been taken care of. Someone has taken the time to keep it simple and orderly. They have paid appropriate attention to details. They have cared.” Simply, it is a quest for code that is easy to understand and easy to maintain.
  • 5. "Any fool can write code that a computer can understand. Good programmers write code that humans can understand." - Martin Fowler
  • 6. Lower the Cognitive Load In cognitive psychology, cognitive load refers to the total amount of mental effort being used in the working memory. Cognitive load theory was developed out of the study of problem solving by John Sweller in the late 1980s Wikipedia: https://en.wikipedia.org/wiki/Cognitive_load
  • 7. Lower the Cognitive Load When reading code, make it easier on yourself: ● Abstract complexity ● Single responsibility ● Short, sweet and to the point ● Be Consistent ● Explanatory Variables and Function Names ● Structure your Code to help readability ● Use Coding Conventions
  • 8. Don’t suffocate your code, let it breathe ● When reading code, white space can be your friend. ● Let whitespace separate code that should be separated ● Let the lack of whitespace help you decide what code is connected.
  • 9. General Rules of Clean Code ● Remember, you write code one time, while the same code might be read hundreds of times… code for the primary use case… make it readable. ● Decide on conventions, and stick to them. ● Coding by yourself overtime isn’t easy, in a team, it can be a nightmare. ● KISS - Keep it Simple Stupid ● Boy Scout Rules - Leave it cleaner than you found it ● Look past the symptom, find the root problem or cause.
  • 10. Naming Rules There is a saying, that there are 2 really hard things in software engineering ● Cache Invalidation ● Naming things ● And 1 off errors They were right, naming things is really hard. Let’s look at some rules to help with Naming
  • 11. Naming Rules ● Choose descriptive and unambiguous names. ● Make names meaningful and distinct. ● Use pronounceable names. ● Use searchable names. ● Replace magic numbers with named constants. ● Try to avoid encodings and prefixes or type information ● Don’t use Acronyms unless they are universal like URL.
  • 12. Naming - Meaningful distinct name -- Do This -- customerAddress = getCustomerAddress() dangerColor = ‘##FF0000’ -- Not this -- Ca = CustAddDetails() redColor = “##FF0000”
  • 13. Naming - Constants They should all be in uppercase separated by underscores "_". Examples: -- DO THIS -- INTERCEPTOR_POINTS = ""; LINE_SEP = "-"; MAX = "123"; -- NOT THIS -- interceptor-points = ""; line_sep = "d"; max = "123";
  • 14. Naming - Acronyms and Abbreviations -- DO THIS -- URLScanner.cfc parseHTTPString() -- NOT THIS -- url-scanner.cfc UrlScanner.cfc parseHttpString() ParseHttpString()
  • 15. Naming - avoid prefixes suffixes -- Do This -- dayOfWeek = “thursday” aUsers = getUsers( { active = true } ); -- Not this -- strDow = “thursday” User-array = getUsers( { active = true } );
  • 16. Functions ● Keep the function Short and Sweet ● Single responsibility - do one thing ● Functions have names, use the same rules for naming functions ● Try not to have too many arguments - use structs for more options. ● Keep side effects to a minimum ● Don’t use Flag arguments ○ Use separate methods that can be called from the client ● Use functions to hide complexity, to keep other functions short, sweet, and easier to understand
  • 17. Functions - Too many arguments --Do this -- searchCars( { seats=4, minPrice = 20,000 } ) -- Not this -- searchCars( seats, color, maxPrice, minPrice, type, make )
  • 18. Functions - Avoid Side Effects https://github.com/ryanmcdermott/clean-code-javascript#avoid-side-effects-part-1
  • 19. Functions - Don’t use Flags - Bad function createFile(name, temp) { if (temp) { fs.create(`./temp/${name}`); } else { fs.create(name); } }
  • 20. Functions - Don’t use Flags - Good function createFile(name) { fs.create(name); } function createTempFile(name) { createFile(`./temp/${name}`); }
  • 21. Comments ● Try and let code speak for you where possible ● Comments should add value and meaning to the code ● Don’t add a comment that is redundant - ie save user ● Don’t add comments just to add them, add value ● Add comments in advance, not on closing braces ● Don’t comment out code, remove it, that’s what Git is for ● Explain the intent, not the actual implementation ● Useful when explaining consequences or ramifications ● ColdDoc will generate docs from javadoc styled comments ○ https://github.com/Ortus-Solutions/commandbox/blob/development/src/cfml/system/BaseCom mand.cfc ○ http://apidocs.ortussolutions.com/commandbox/3.7.0/index.html
  • 22. Structuring your Source Code ● Separate your Code Concepts vertically in your Files ● Variables should be declared close to where they are being used ○ This has changed from the old days, where top of the function was the preference. Although, which a short function, top should be close ;) ● Functions that are Dependant should be close to each other ● Similar functions should be close to each other ● Use indention consistently
  • 23. Formatting ● Everyone in the team should use the same conventions ● If the language has conventions, use that ○ CFML doesn’t, that’s why Ortus has made theirs public. https://github.com/Ortus-Solutions/coding-standards ● Keep Lines short ● Don’t modify a file just to format it… if you are adding to the file, then format it
  • 24. Resources Ortus Conventions: https://github.com/Ortus-Solutions/coding-standards Uncle Bob’s Clean Code on Amazon: http://amzn.to/2tfKL9C Javascript Clean Code: https://github.com/ryanmcdermott/clean-code-javascript Clean Code course on Pluralsight: https://www.pluralsight.com/courses/writing-clean-code-humans
  • 25. Too much text Not enough code? Lets try a live example - live code - we’re living dangerously https://github.com/elpete/cb-module- template/blob/master/commands/mo dule/scaffold.cfc