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 development
Vasco Veloso
 
Tools and techniques for APIs
Tools and techniques for APIsTools and techniques for APIs
Tools and techniques for APIs
Jason 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 APIs
Kong 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 pipeline
Pronovix
 
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 class
LibbySchulze
 
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 Spec
Adam Paxton
 
Api guide
Api guide Api guide
Api guide
Deepak Rai
 
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 Matter
Joel 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, Netflix
apidays
 
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
Jeremy Whitlock
 
Swagger for-your-api
Swagger for-your-apiSwagger for-your-api
Swagger for-your-api
Tony Tam
 
TRAX technical highlights
TRAX technical highlightsTRAX technical highlights
TRAX technical highlights
ESUG
 
Automating the API Product Lifecycle
Automating the API Product LifecycleAutomating the API Product Lifecycle
Automating the API Product Lifecycle
Pronovix
 
Open Event API
Open Event APIOpen Event API
Open Event API
Avi 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.pptx
MukundSonaiya1
 
Writing Readable Code
Writing Readable CodeWriting Readable Code
Writing Readable Code
eddiehaber
 
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 clean
Hector Canto
 
Writing clean scientific software Murphy cleancoding
Writing clean scientific software Murphy cleancodingWriting clean scientific software Murphy cleancoding
Writing clean scientific software Murphy cleancoding
saber tabatabaee
 
Software Craftmanship - Cours Polytech
Software Craftmanship - Cours PolytechSoftware Craftmanship - Cours Polytech
Software Craftmanship - Cours Polytech
yannick grenzinger
 
Good Coding Practices with JavaScript
Good Coding Practices with JavaScriptGood Coding Practices with JavaScript
Good Coding Practices with JavaScript
🏁 Pierre-Henry Soria 💡
 
Software development best practices & coding guidelines
Software development best practices & coding guidelinesSoftware development best practices & coding guidelines
Software development best practices & coding guidelines
Ankur Goyal
 
How to write good quality code
How to write good quality codeHow to write good quality code
How to write good quality code
Hayden Bleasel
 
YAGNI Principle and Clean Code
YAGNI Principle and Clean CodeYAGNI Principle and Clean Code
YAGNI Principle and Clean Code
Luan Reffatti
 
engage 2014 - JavaBlast
engage 2014 - JavaBlastengage 2014 - JavaBlast
engage 2014 - JavaBlast
René Winkelmeyer
 
Half-automatic Compilable Source Code Recovery
Half-automatic Compilable Source Code RecoveryHalf-automatic Compilable Source Code Recovery
Half-automatic Compilable Source Code Recovery
Joxean Koret
 
DDD with Behat
DDD with BehatDDD with Behat
DDD with Behat
Anton Serdyuk
 
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
maiktoepfer
 
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 2012
cobyst
 
Code Review
Code ReviewCode Review
Code Review
Erik Ecoologic
 
Clean code and code smells
Clean code and code smellsClean code and code smells
Clean code and code smells
Md. Aftab Uddin Kajal
 
WordCamp Nashville: Clean Code for WordPress
WordCamp Nashville: Clean Code for WordPressWordCamp Nashville: Clean Code for WordPress
WordCamp Nashville: Clean Code for WordPress
mtoppa
 
The View - Lotusscript coding best practices
The View - Lotusscript coding best practicesThe View - Lotusscript coding best practices
The View - Lotusscript coding best practices
Bill 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 Pickin
Gavin Pickin
 
Containerizing ContentBox CMS
Containerizing ContentBox CMSContainerizing ContentBox CMS
Containerizing ContentBox CMS
Gavin 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 API
Gavin 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, 2016
Gavin 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 Client
Gavin Pickin
 
Just Mock It - Mocks and Stubs
Just Mock It - Mocks and StubsJust Mock It - Mocks and Stubs
Just Mock It - Mocks and Stubs
Gavin 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 Cordova
Gavin 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 ColdFusion
Gavin 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

Bangalore Call Girls 9079923931 With -Cuties' Hot Call Girls
Bangalore Call Girls 9079923931 With -Cuties' Hot Call GirlsBangalore Call Girls 9079923931 With -Cuties' Hot Call Girls
Bangalore Call Girls 9079923931 With -Cuties' Hot Call Girls
narwatsonia7
 
Decentralized Justice in Gaming and Esports
Decentralized Justice in Gaming and EsportsDecentralized Justice in Gaming and Esports
Decentralized Justice in Gaming and Esports
Federico Ast
 
Unlimited Fun With Call Girls Hyderabad ✅ 7737669865 💘 FULL CASH PAYMENT
Unlimited Fun With Call Girls Hyderabad ✅ 7737669865 💘 FULL CASH PAYMENTUnlimited Fun With Call Girls Hyderabad ✅ 7737669865 💘 FULL CASH PAYMENT
Unlimited Fun With Call Girls Hyderabad ✅ 7737669865 💘 FULL CASH PAYMENT
keshavtiwari584
 
Honeypots Unveiled: Proactive Defense Tactics for Cyber Security, Phoenix Sum...
Honeypots Unveiled: Proactive Defense Tactics for Cyber Security, Phoenix Sum...Honeypots Unveiled: Proactive Defense Tactics for Cyber Security, Phoenix Sum...
Honeypots Unveiled: Proactive Defense Tactics for Cyber Security, Phoenix Sum...
APNIC
 
一比一原版圣托马斯大学毕业证(UST毕业证书)学历如何办理
一比一原版圣托马斯大学毕业证(UST毕业证书)学历如何办理一比一原版圣托马斯大学毕业证(UST毕业证书)学历如何办理
一比一原版圣托马斯大学毕业证(UST毕业证书)学历如何办理
uqbyfm
 
169+ Call Girls In Navi Mumbai | 9930245274 | Reliability Escort Service Near...
169+ Call Girls In Navi Mumbai | 9930245274 | Reliability Escort Service Near...169+ Call Girls In Navi Mumbai | 9930245274 | Reliability Escort Service Near...
169+ Call Girls In Navi Mumbai | 9930245274 | Reliability Escort Service Near...
tanichadda371 #v08
 
IPv6: Unlocking the Potential, presented by Paul Wilson at CommunicAsia 2024
IPv6: Unlocking the Potential, presented by Paul Wilson at CommunicAsia 2024IPv6: Unlocking the Potential, presented by Paul Wilson at CommunicAsia 2024
IPv6: Unlocking the Potential, presented by Paul Wilson at CommunicAsia 2024
APNIC
 
India Cyber Threat Report of 2024 with year
India Cyber Threat Report of 2024 with yearIndia Cyber Threat Report of 2024 with year
India Cyber Threat Report of 2024 with year
AkashKumar1733
 
The Principal Up-and-Coming Risks to Cloud-Based Security!
The Principal Up-and-Coming Risks to Cloud-Based Security!The Principal Up-and-Coming Risks to Cloud-Based Security!
The Principal Up-and-Coming Risks to Cloud-Based Security!
Alec Kassir cozmozone
 
peru primero de la alianza con el pacifico
peru primero de la alianza con el pacificoperu primero de la alianza con el pacifico
peru primero de la alianza con el pacifico
FernandoGuevaraVentu2
 
一比一原版新西兰林肯大学毕业证(Lincoln毕业证书)学历如何办理
一比一原版新西兰林肯大学毕业证(Lincoln毕业证书)学历如何办理一比一原版新西兰林肯大学毕业证(Lincoln毕业证书)学历如何办理
一比一原版新西兰林肯大学毕业证(Lincoln毕业证书)学历如何办理
thezot
 
Securing BGP: Operational Strategies and Best Practices for Network Defenders...
Securing BGP: Operational Strategies and Best Practices for Network Defenders...Securing BGP: Operational Strategies and Best Practices for Network Defenders...
Securing BGP: Operational Strategies and Best Practices for Network Defenders...
APNIC
 
Lesson6 in spreadsheet 2024 for g12..ppt
Lesson6 in spreadsheet 2024 for g12..pptLesson6 in spreadsheet 2024 for g12..ppt
Lesson6 in spreadsheet 2024 for g12..ppt
ReyLouieSedigo1
 
KubeCon & CloudNative Con 2024 Artificial Intelligent
KubeCon & CloudNative Con 2024 Artificial IntelligentKubeCon & CloudNative Con 2024 Artificial Intelligent
KubeCon & CloudNative Con 2024 Artificial Intelligent
Emre Gündoğdu
 
10 Conversion Rate Optimization (CRO) Techniques to Boost Your Website’s Perf...
10 Conversion Rate Optimization (CRO) Techniques to Boost Your Website’s Perf...10 Conversion Rate Optimization (CRO) Techniques to Boost Your Website’s Perf...
10 Conversion Rate Optimization (CRO) Techniques to Boost Your Website’s Perf...
Web Inspire
 
DocSplit Subsequent Implementation Activation.pptx
DocSplit Subsequent Implementation Activation.pptxDocSplit Subsequent Implementation Activation.pptx
DocSplit Subsequent Implementation Activation.pptx
AmitTuteja9
 
EASY TUTORIAL OF HOW TO USE CiCi AI BY: FEBLESS HERNANE
EASY TUTORIAL OF HOW TO USE CiCi AI BY: FEBLESS HERNANE EASY TUTORIAL OF HOW TO USE CiCi AI BY: FEBLESS HERNANE
EASY TUTORIAL OF HOW TO USE CiCi AI BY: FEBLESS HERNANE
Febless Hernane
 
Unlimited Short Call Girls Mumbai ✅ 9833363713 FULL CASH PAYMENT
Unlimited Short Call Girls Mumbai ✅ 9833363713 FULL CASH PAYMENTUnlimited Short Call Girls Mumbai ✅ 9833363713 FULL CASH PAYMENT
Unlimited Short Call Girls Mumbai ✅ 9833363713 FULL CASH PAYMENT
rajesh344555
 
cyber crime.pptx..........................
cyber crime.pptx..........................cyber crime.pptx..........................
cyber crime.pptx..........................
GNAMBIKARAO
 
HistorySrSec2024 daahi sadhin sgg-25.pdf
HistorySrSec2024 daahi sadhin sgg-25.pdfHistorySrSec2024 daahi sadhin sgg-25.pdf
HistorySrSec2024 daahi sadhin sgg-25.pdf
AdiySgh
 

Recently uploaded (20)

Bangalore Call Girls 9079923931 With -Cuties' Hot Call Girls
Bangalore Call Girls 9079923931 With -Cuties' Hot Call GirlsBangalore Call Girls 9079923931 With -Cuties' Hot Call Girls
Bangalore Call Girls 9079923931 With -Cuties' Hot Call Girls
 
Decentralized Justice in Gaming and Esports
Decentralized Justice in Gaming and EsportsDecentralized Justice in Gaming and Esports
Decentralized Justice in Gaming and Esports
 
Unlimited Fun With Call Girls Hyderabad ✅ 7737669865 💘 FULL CASH PAYMENT
Unlimited Fun With Call Girls Hyderabad ✅ 7737669865 💘 FULL CASH PAYMENTUnlimited Fun With Call Girls Hyderabad ✅ 7737669865 💘 FULL CASH PAYMENT
Unlimited Fun With Call Girls Hyderabad ✅ 7737669865 💘 FULL CASH PAYMENT
 
Honeypots Unveiled: Proactive Defense Tactics for Cyber Security, Phoenix Sum...
Honeypots Unveiled: Proactive Defense Tactics for Cyber Security, Phoenix Sum...Honeypots Unveiled: Proactive Defense Tactics for Cyber Security, Phoenix Sum...
Honeypots Unveiled: Proactive Defense Tactics for Cyber Security, Phoenix Sum...
 
一比一原版圣托马斯大学毕业证(UST毕业证书)学历如何办理
一比一原版圣托马斯大学毕业证(UST毕业证书)学历如何办理一比一原版圣托马斯大学毕业证(UST毕业证书)学历如何办理
一比一原版圣托马斯大学毕业证(UST毕业证书)学历如何办理
 
169+ Call Girls In Navi Mumbai | 9930245274 | Reliability Escort Service Near...
169+ Call Girls In Navi Mumbai | 9930245274 | Reliability Escort Service Near...169+ Call Girls In Navi Mumbai | 9930245274 | Reliability Escort Service Near...
169+ Call Girls In Navi Mumbai | 9930245274 | Reliability Escort Service Near...
 
IPv6: Unlocking the Potential, presented by Paul Wilson at CommunicAsia 2024
IPv6: Unlocking the Potential, presented by Paul Wilson at CommunicAsia 2024IPv6: Unlocking the Potential, presented by Paul Wilson at CommunicAsia 2024
IPv6: Unlocking the Potential, presented by Paul Wilson at CommunicAsia 2024
 
India Cyber Threat Report of 2024 with year
India Cyber Threat Report of 2024 with yearIndia Cyber Threat Report of 2024 with year
India Cyber Threat Report of 2024 with year
 
The Principal Up-and-Coming Risks to Cloud-Based Security!
The Principal Up-and-Coming Risks to Cloud-Based Security!The Principal Up-and-Coming Risks to Cloud-Based Security!
The Principal Up-and-Coming Risks to Cloud-Based Security!
 
peru primero de la alianza con el pacifico
peru primero de la alianza con el pacificoperu primero de la alianza con el pacifico
peru primero de la alianza con el pacifico
 
一比一原版新西兰林肯大学毕业证(Lincoln毕业证书)学历如何办理
一比一原版新西兰林肯大学毕业证(Lincoln毕业证书)学历如何办理一比一原版新西兰林肯大学毕业证(Lincoln毕业证书)学历如何办理
一比一原版新西兰林肯大学毕业证(Lincoln毕业证书)学历如何办理
 
Securing BGP: Operational Strategies and Best Practices for Network Defenders...
Securing BGP: Operational Strategies and Best Practices for Network Defenders...Securing BGP: Operational Strategies and Best Practices for Network Defenders...
Securing BGP: Operational Strategies and Best Practices for Network Defenders...
 
Lesson6 in spreadsheet 2024 for g12..ppt
Lesson6 in spreadsheet 2024 for g12..pptLesson6 in spreadsheet 2024 for g12..ppt
Lesson6 in spreadsheet 2024 for g12..ppt
 
KubeCon & CloudNative Con 2024 Artificial Intelligent
KubeCon & CloudNative Con 2024 Artificial IntelligentKubeCon & CloudNative Con 2024 Artificial Intelligent
KubeCon & CloudNative Con 2024 Artificial Intelligent
 
10 Conversion Rate Optimization (CRO) Techniques to Boost Your Website’s Perf...
10 Conversion Rate Optimization (CRO) Techniques to Boost Your Website’s Perf...10 Conversion Rate Optimization (CRO) Techniques to Boost Your Website’s Perf...
10 Conversion Rate Optimization (CRO) Techniques to Boost Your Website’s Perf...
 
DocSplit Subsequent Implementation Activation.pptx
DocSplit Subsequent Implementation Activation.pptxDocSplit Subsequent Implementation Activation.pptx
DocSplit Subsequent Implementation Activation.pptx
 
EASY TUTORIAL OF HOW TO USE CiCi AI BY: FEBLESS HERNANE
EASY TUTORIAL OF HOW TO USE CiCi AI BY: FEBLESS HERNANE EASY TUTORIAL OF HOW TO USE CiCi AI BY: FEBLESS HERNANE
EASY TUTORIAL OF HOW TO USE CiCi AI BY: FEBLESS HERNANE
 
Unlimited Short Call Girls Mumbai ✅ 9833363713 FULL CASH PAYMENT
Unlimited Short Call Girls Mumbai ✅ 9833363713 FULL CASH PAYMENTUnlimited Short Call Girls Mumbai ✅ 9833363713 FULL CASH PAYMENT
Unlimited Short Call Girls Mumbai ✅ 9833363713 FULL CASH PAYMENT
 
cyber crime.pptx..........................
cyber crime.pptx..........................cyber crime.pptx..........................
cyber crime.pptx..........................
 
HistorySrSec2024 daahi sadhin sgg-25.pdf
HistorySrSec2024 daahi sadhin sgg-25.pdfHistorySrSec2024 daahi sadhin sgg-25.pdf
HistorySrSec2024 daahi sadhin sgg-25.pdf
 

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