SlideShare a Scribd company logo
1 of 27
Download to read offline
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 - CFObjective() 2017
AN EXERCISE IN CLEANER CODE - FROM LEGACY TO MAINTAINABLE - CFObjective() 2017

More Related Content

What's hot

Роман Лютиков "Web Apps Performance & JavaScript Compilers"
Роман Лютиков "Web Apps Performance & JavaScript Compilers"Роман Лютиков "Web Apps Performance & JavaScript Compilers"
Роман Лютиков "Web Apps Performance & JavaScript Compilers"
Fwdays
 
Олексій Павленко. CONTRACT PROTECTION ON THE FRONTEND SIDE: HOW TO ORGANIZE R...
Олексій Павленко. CONTRACT PROTECTION ON THE FRONTEND SIDE: HOW TO ORGANIZE R...Олексій Павленко. CONTRACT PROTECTION ON THE FRONTEND SIDE: HOW TO ORGANIZE R...
Олексій Павленко. CONTRACT PROTECTION ON THE FRONTEND SIDE: HOW TO ORGANIZE R...
OdessaJS Conf
 

What's hot (20)

DDD with Behat
DDD with BehatDDD with Behat
DDD with Behat
 
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
 
Automated Testing with Cucumber, PhantomJS and Selenium
Automated Testing with Cucumber, PhantomJS and SeleniumAutomated Testing with Cucumber, PhantomJS and Selenium
Automated Testing with Cucumber, PhantomJS and Selenium
 
Test all the things! Automated testing with Drupal 8
Test all the things! Automated testing with Drupal 8Test all the things! Automated testing with Drupal 8
Test all the things! Automated testing with Drupal 8
 
Securing Legacy CFML Code
Securing Legacy CFML CodeSecuring Legacy CFML Code
Securing Legacy CFML Code
 
Testing of React JS app
Testing of React JS appTesting of React JS app
Testing of React JS app
 
Test automation with cucumber jvm
Test automation with cucumber jvmTest automation with cucumber jvm
Test automation with cucumber jvm
 
Jest: Frontend Testing leicht gemacht @EnterJS2018
Jest: Frontend Testing leicht gemacht @EnterJS2018Jest: Frontend Testing leicht gemacht @EnterJS2018
Jest: Frontend Testing leicht gemacht @EnterJS2018
 
Efficient JavaScript Unit Testing, May 2012
Efficient JavaScript Unit Testing, May 2012Efficient JavaScript Unit Testing, May 2012
Efficient JavaScript Unit Testing, May 2012
 
Yet Another Continuous Integration Story
Yet Another Continuous Integration StoryYet Another Continuous Integration Story
Yet Another Continuous Integration Story
 
Роман Лютиков "Web Apps Performance & JavaScript Compilers"
Роман Лютиков "Web Apps Performance & JavaScript Compilers"Роман Лютиков "Web Apps Performance & JavaScript Compilers"
Роман Лютиков "Web Apps Performance & JavaScript Compilers"
 
Test-Driven JavaScript Development (JavaZone 2010)
Test-Driven JavaScript Development (JavaZone 2010)Test-Driven JavaScript Development (JavaZone 2010)
Test-Driven JavaScript Development (JavaZone 2010)
 
Living With Legacy Code
Living With Legacy CodeLiving With Legacy Code
Living With Legacy Code
 
Can you contain the future - Docker, Container Technologies, The Future, and You
Can you contain the future - Docker, Container Technologies, The Future, and YouCan you contain the future - Docker, Container Technologies, The Future, and You
Can you contain the future - Docker, Container Technologies, The Future, and You
 
Buildr - build like you code
Buildr -  build like you codeBuildr -  build like you code
Buildr - build like you code
 
Олексій Павленко. CONTRACT PROTECTION ON THE FRONTEND SIDE: HOW TO ORGANIZE R...
Олексій Павленко. CONTRACT PROTECTION ON THE FRONTEND SIDE: HOW TO ORGANIZE R...Олексій Павленко. CONTRACT PROTECTION ON THE FRONTEND SIDE: HOW TO ORGANIZE R...
Олексій Павленко. CONTRACT PROTECTION ON THE FRONTEND SIDE: HOW TO ORGANIZE R...
 
Groovy and noteworthy
Groovy and noteworthyGroovy and noteworthy
Groovy and noteworthy
 
Testing Legacy Rails Apps
Testing Legacy Rails AppsTesting Legacy Rails Apps
Testing Legacy Rails Apps
 
Hack & Fix, Hands on ColdFusion Security Training
Hack & Fix, Hands on ColdFusion Security TrainingHack & Fix, Hands on ColdFusion Security Training
Hack & Fix, Hands on ColdFusion Security Training
 
C# 6
C# 6C# 6
C# 6
 

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

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
 
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 - CFObjective() 2017 (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
 
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
 
Fuzzing - Part 2
Fuzzing - Part 2Fuzzing - Part 2
Fuzzing - Part 2
 

More from Ortus Solutions, Corp

More from Ortus Solutions, Corp (20)

BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
Ortus Government.pdf
Ortus Government.pdfOrtus Government.pdf
Ortus Government.pdf
 
Luis Majano The Battlefield ORM
Luis Majano The Battlefield ORMLuis Majano The Battlefield ORM
Luis Majano The Battlefield ORM
 
Brad Wood - CommandBox CLI
Brad Wood - CommandBox CLI Brad Wood - CommandBox CLI
Brad Wood - CommandBox CLI
 
Secure your Secrets and Settings in ColdFusion
Secure your Secrets and Settings in ColdFusionSecure your Secrets and Settings in ColdFusion
Secure your Secrets and Settings in ColdFusion
 
Daniel Garcia ContentBox: CFSummit 2023
Daniel Garcia ContentBox: CFSummit 2023Daniel Garcia ContentBox: CFSummit 2023
Daniel Garcia ContentBox: CFSummit 2023
 
ITB_2023_Human-Friendly_Scheduled_Tasks_Giancarlo_Gomez.pdf
ITB_2023_Human-Friendly_Scheduled_Tasks_Giancarlo_Gomez.pdfITB_2023_Human-Friendly_Scheduled_Tasks_Giancarlo_Gomez.pdf
ITB_2023_Human-Friendly_Scheduled_Tasks_Giancarlo_Gomez.pdf
 
ITB_2023_CommandBox_Multi-Server_-_Brad_Wood.pdf
ITB_2023_CommandBox_Multi-Server_-_Brad_Wood.pdfITB_2023_CommandBox_Multi-Server_-_Brad_Wood.pdf
ITB_2023_CommandBox_Multi-Server_-_Brad_Wood.pdf
 
ITB_2023_The_Many_Layers_of_OAuth_Keith_Casey_.pdf
ITB_2023_The_Many_Layers_of_OAuth_Keith_Casey_.pdfITB_2023_The_Many_Layers_of_OAuth_Keith_Casey_.pdf
ITB_2023_The_Many_Layers_of_OAuth_Keith_Casey_.pdf
 
ITB_2023_Relationships_are_Hard_Data_modeling_with_NoSQL_Curt_Gratz.pdf
ITB_2023_Relationships_are_Hard_Data_modeling_with_NoSQL_Curt_Gratz.pdfITB_2023_Relationships_are_Hard_Data_modeling_with_NoSQL_Curt_Gratz.pdf
ITB_2023_Relationships_are_Hard_Data_modeling_with_NoSQL_Curt_Gratz.pdf
 
ITB_2023_Extend_your_contentbox_apps_with_custom_modules_Javier_Quintero.pdf
ITB_2023_Extend_your_contentbox_apps_with_custom_modules_Javier_Quintero.pdfITB_2023_Extend_your_contentbox_apps_with_custom_modules_Javier_Quintero.pdf
ITB_2023_Extend_your_contentbox_apps_with_custom_modules_Javier_Quintero.pdf
 
ITB_2023_25_Most_Dangerous_Software_Weaknesses_Pete_Freitag.pdf
ITB_2023_25_Most_Dangerous_Software_Weaknesses_Pete_Freitag.pdfITB_2023_25_Most_Dangerous_Software_Weaknesses_Pete_Freitag.pdf
ITB_2023_25_Most_Dangerous_Software_Weaknesses_Pete_Freitag.pdf
 
ITB_2023_CBWire_v3_Grant_Copley.pdf
ITB_2023_CBWire_v3_Grant_Copley.pdfITB_2023_CBWire_v3_Grant_Copley.pdf
ITB_2023_CBWire_v3_Grant_Copley.pdf
 
ITB_2023_Practical_AI_with_OpenAI_-_Grant_Copley_.pdf
ITB_2023_Practical_AI_with_OpenAI_-_Grant_Copley_.pdfITB_2023_Practical_AI_with_OpenAI_-_Grant_Copley_.pdf
ITB_2023_Practical_AI_with_OpenAI_-_Grant_Copley_.pdf
 
ITB_2023_When_Your_Applications_Work_As_a_Team_Nathaniel_Francis.pdf
ITB_2023_When_Your_Applications_Work_As_a_Team_Nathaniel_Francis.pdfITB_2023_When_Your_Applications_Work_As_a_Team_Nathaniel_Francis.pdf
ITB_2023_When_Your_Applications_Work_As_a_Team_Nathaniel_Francis.pdf
 
ITB_2023_Faster_Apps_That_Wont_Get_Crushed_Brian_Klaas.pdf
ITB_2023_Faster_Apps_That_Wont_Get_Crushed_Brian_Klaas.pdfITB_2023_Faster_Apps_That_Wont_Get_Crushed_Brian_Klaas.pdf
ITB_2023_Faster_Apps_That_Wont_Get_Crushed_Brian_Klaas.pdf
 
ITB_2023_Chatgpt_Box_Scott_Steinbeck.pdf
ITB_2023_Chatgpt_Box_Scott_Steinbeck.pdfITB_2023_Chatgpt_Box_Scott_Steinbeck.pdf
ITB_2023_Chatgpt_Box_Scott_Steinbeck.pdf
 
ITB_2023_CommandBox_Task_Runners_Brad_Wood.pdf
ITB_2023_CommandBox_Task_Runners_Brad_Wood.pdfITB_2023_CommandBox_Task_Runners_Brad_Wood.pdf
ITB_2023_CommandBox_Task_Runners_Brad_Wood.pdf
 
ITB_2023_Create_as_many_web_sites_or_web_apps_as_you_want_George_Murphy.pdf
ITB_2023_Create_as_many_web_sites_or_web_apps_as_you_want_George_Murphy.pdfITB_2023_Create_as_many_web_sites_or_web_apps_as_you_want_George_Murphy.pdf
ITB_2023_Create_as_many_web_sites_or_web_apps_as_you_want_George_Murphy.pdf
 
ITB2023 Developing for Performance - Denard Springle.pdf
ITB2023 Developing for Performance - Denard Springle.pdfITB2023 Developing for Performance - Denard Springle.pdf
ITB2023 Developing for Performance - Denard Springle.pdf
 

Recently uploaded

Recently uploaded (20)

Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
🐬 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
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024
 
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
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
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
 
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...
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
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
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 

AN EXERCISE IN CLEANER CODE - FROM LEGACY TO MAINTAINABLE - CFObjective() 2017

  • 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