SlideShare a Scribd company logo
CLEAN CODE PRINCIPLES
VLADIMIR
ROMANOV
#YeurDreamin2019
About me
• Salesforce Platform Developer
• Hanging out in the cloud since 2014
• Big and small projects
• Currently based in Berlin (SumUp)
Vladimir Romanov
SAFE HARBOR…
#YeurDreamin2019
WHAT IS CLEAN CODE?
• Human Readable
• Easy to change and maintain
#YeurDreamin2019
Messy code
#YeurDreamin2019
CLEAN CODE PRINCIPLES
0. The Boy Scout rule
1. Meaningful Naming
2. Constants instead of Hard-Coded Strings or Integers
3. Small Functions
#YeurDreamin2019
BOY SCOUT RULE
• Always leave the campground cleaner than you found it. (Boy Scouts)
• Always leave the code you’re editing a little better than you found it.
(Robert C. Martin)
 Take responsibility of the environment
 There is no ideal code – there is better code
=
#YeurDreamin2019
#1 MEANINGFUL NAMING
• Descriptive, Intention-Revealing
• Use words, not abbreviations
 Better long than ambiguous
• Searchable
a -> accountRecord
genymdhms -> generationTimestamp
#YeurDreamin2019
Slide title
• First level 1
 Second level 2
#YeurDreamin2019
Descriptive Names
• Class Names
 Noun or noun phrase like Customer, WikiPage
 Avoid generic words like Manager, Processor, Data, Info
• Method Names Should Say What They Do
 verb or verb phrase names like postPayment, deletePage, or save.
 doRename() -> renamePage(), renamePageAndOptionallyAllReferences()
#YeurDreamin2019
Naming considerations
• Having variable type as part of name
 Account parentAccount;
 Button resetButton;
• Using plural names for arrays/collections of objects
 List or Set can be omitted if sets usually contain unique primitive type
values and lists contain non-unique complex objects
 userList -> users
 List<FollowUp__c> followUps;
 Set<Id> accountIds;
#YeurDreamin2019
Naming considerations
• Define and follow a Naming convention per project, for example:
 Use CamelCase (sendSMS -> sendSms)
 Variable and method names start with lowercase letter (accountRecord,
accounts)
 Class names start with uppercase letter (Account)
 Constants written in uppercase separated with underscore
(DAYS_IN_WEEK, SOBJECTTYPE_CASE, STR_OK)
#YeurDreamin2019
Naming considerations
• Re-evaluate names as software evolves
• Respect Encapsulation
 Add public access or {get;set;} only when necessary. Use private
variables by default.
 Private variables are easier to change – they are referenced only inside
the class
#YeurDreamin2019
Naming considerations
• Use variables as a way to say more about what the code is doing
• Break the calculations up into intermediate values that are held in
variables with meaningful names.
Matcher match = headerPattern.matcher(line);
if(match.find()) {
String key = match.group(1);
String value = match.group(2);
headers.put(key.toLowerCase(), value);
}
#YeurDreamin2019
#2 CONSTANTS INSTEAD OF HARD-CODED STRINGS OR INTEGERS
• Use constant variables instead of hardcoded Strings or Numbers
 DAYS_IN_WEEK instead of 7
 COMPANY_CODE_ITALY instead of ‘485’
• Give them a descriptive name using UPPER CASE
• Define all the constants at the top of the class
• Consider using a class to contain global constants.
• Consider getting value for constants from Custom Labels or Custom
Metadata
• Easier to
 Read
 Search
 Change value
 Test
#YeurDreamin2019
#3 SMALL FUNCTIONS
• Use Small Functions – split a larger function into smaller ones by
looking at
 logical sections
 levels of indentation
 Rule of thumb - Every Function should do One thing and do it well
 Does one thing
 Separates levels of abstraction
 Easier to
 Understand
 Modify
 Reuse, reduce duplication
 Test
• The less arguments the better (ideally <= 2)
 Use instance / static variables to pass frequently used data
 Use DTO classes to encapsulate parameters – e.g. InitDataDto,
AddressWrapper, RequestWrapper
#YeurDreamin2019
Applying the principles - Clean Conditionals
• Encapsulate conditionals
 if (timer.hasExpired() && !timer.isRecurrent()) -> if (shouldBeDeleted(timer))
• Encapsulate boundary conditionals
 level + 1 < tags.length -> if(nextLevel < tags.length)
• Avoid Negative Conditionals
 if ( !followUpNeeded() ) -> if ( followUpNotNeeded() )
• Use standard apex methods for null checks and empty lists checks
 myString != null && myString!=‘’ -> String.isNotEmpty(myString)
 myList.size()==0 -> myList.isEmpty()
 $A.util.isEmpty(value) – in Lightning components
#YeurDreamin2019
Applying the principles - Clean SOQL
• Format SOQL queries
• Use a separate function for each SOQL query, adding all fields on
separate lines in the alphabetical order
• Place the function at the end of class or use a Data Access Layer class to
reuse queries
 allows to reuse it
 Easier to add fields
 Better maintenance
private static List<Account> retrieveAccountsByIds (Set<Id>
accountIds)
{
return
[
SELECT
Id,
Name
FROM Account
WHERE Id IN :accountIds
];
}
#YeurDreamin2019
Applying the principles - Clean Loops and Branches
• Keep indentation at max 2 levels
• an if else chain inside a function may mean it is doing more than one thing
• Too many branch levels may mean working on different levels of
abstraction, which makes harder to read and easier to miss something
• Use loop control statements like break; and continue; statements to
reduce indentation
for (WRP_Email emailWrapper : emailWrappers) {
if (emailWrapper.hasPropertyRequest()) {
Id plotId = getPlotIdFromEmail(emailWrapper);
if (plotId!= null)
plotIds.add(plotId);
}
}
->
for (WRP_Email emailWrapper : emailWrappers) {
if (emailWrapper.hasNoPropertyRequest())
continue;
Id plotId = getPlotIdFromEmail(emailWrapper);
if (plotId!= null)
plotIds.add(plotId);
}
#YeurDreamin2019
Applying the principles - Clean comments
• Clean code often doesn’t need comments!
 Don’t use trivial/redundant comments
 Delete outdated comments when software evolves (saving them in git
repository)
#YeurDreamin2019
Applying the principles - Clean debugging
• Write class name and method name in debug message
 System.debug(‘MyClass::myFunction()::myVariable: ’+myVariable);
 No need to add the message when names reveal the intention of the class, function and the variable.
 Easier to search in debug log
 Works best when functions are small
SHOW ME MORE CODE!
#YeurDreamin2019
CHANGE OF VISION
• By applying the Clean Code Principles you can See how you can improve
the code and you can do it as you go!
#YeurDreamin2019
Further reading and watching
• Book - Clean Code (Robert C. Martin)
 https://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882
• Pluralsight courses:
 Clean Code: Writing Code for Humans (Cory House)
 https://app.pluralsight.com/library/courses/writing-clean-code-humans
 Maximize Your Value through Salesforce Coding Best Practices
(Matt Kaufman and Don Robins)
 https://app.pluralsight.com/library/courses/play-by-play-maximize-value-through-salesforce-coding-best-
practices/table-of-contents
CODE REVIEW CHALLENGE!
• Make groups of 2-3 people
• Set date and time when you will do a code review together
• Bring some of your code
• Discuss what contributes to readability and maintainability
#YeurDreamin2019
Join us for drinks
@18:00 sponsored
by
Community sponsors:
Stay in touch!
• LinkedIn https://www.linkedin.com/in/vladimir-romanov/
• Twitter @vladfromrome
• YeurDreamin Slack #clean-code
NonProfit-track sponsor:

More Related Content

What's hot

Clean code
Clean codeClean code
Clean code
Duc Nguyen Quang
 
Clean Code
Clean CodeClean Code
Clean Code
swaraj Patil
 
Clean code
Clean codeClean code
Clean code
ifnu bima
 
Clean code
Clean code Clean code
Clean code
Achintya Kumar
 
Clean code
Clean codeClean code
Clean code
Henrique Smoco
 
Writing clean code
Writing clean codeWriting clean code
Writing clean code
Angel Garcia Olloqui
 
Clean Code I - Best Practices
Clean Code I - Best PracticesClean Code I - Best Practices
Clean Code I - Best Practices
Theo Jungeblut
 
Clean Code
Clean CodeClean Code
Clean Code
Dmytro Turskyi
 
Clean Code summary
Clean Code summaryClean Code summary
Clean Code summary
Jan de Vries
 
Clean code
Clean codeClean code
Clean code
Knoldus Inc.
 
Clean Code
Clean CodeClean Code
Clean Code
ISchwarz23
 
Clean Code: Chapter 3 Function
Clean Code: Chapter 3 FunctionClean Code: Chapter 3 Function
Clean Code: Chapter 3 Function
Kent Huang
 
Clean code in JavaScript
Clean code in JavaScriptClean code in JavaScript
Clean code in JavaScript
Mathieu Breton
 
Clean code: meaningful Name
Clean code: meaningful NameClean code: meaningful Name
Clean code: meaningful Namenahid035
 
Clean Code
Clean CodeClean Code
Clean Code
Victor Rentea
 
The Art of Clean code
The Art of Clean codeThe Art of Clean code
The Art of Clean code
Victor Rentea
 
Clean code presentation
Clean code presentationClean code presentation
Clean code presentation
Bhavin Gandhi
 
7 rules of simple and maintainable code
7 rules of simple and maintainable code7 rules of simple and maintainable code
7 rules of simple and maintainable code
Geshan Manandhar
 
C# in depth
C# in depthC# in depth
C# in depth
Arnon Axelrod
 
Clean code: understanding Boundaries and Unit Tests
Clean code: understanding Boundaries and Unit TestsClean code: understanding Boundaries and Unit Tests
Clean code: understanding Boundaries and Unit Tests
radin reth
 

What's hot (20)

Clean code
Clean codeClean code
Clean code
 
Clean Code
Clean CodeClean Code
Clean Code
 
Clean code
Clean codeClean code
Clean code
 
Clean code
Clean code Clean code
Clean code
 
Clean code
Clean codeClean code
Clean code
 
Writing clean code
Writing clean codeWriting clean code
Writing clean code
 
Clean Code I - Best Practices
Clean Code I - Best PracticesClean Code I - Best Practices
Clean Code I - Best Practices
 
Clean Code
Clean CodeClean Code
Clean Code
 
Clean Code summary
Clean Code summaryClean Code summary
Clean Code summary
 
Clean code
Clean codeClean code
Clean code
 
Clean Code
Clean CodeClean Code
Clean Code
 
Clean Code: Chapter 3 Function
Clean Code: Chapter 3 FunctionClean Code: Chapter 3 Function
Clean Code: Chapter 3 Function
 
Clean code in JavaScript
Clean code in JavaScriptClean code in JavaScript
Clean code in JavaScript
 
Clean code: meaningful Name
Clean code: meaningful NameClean code: meaningful Name
Clean code: meaningful Name
 
Clean Code
Clean CodeClean Code
Clean Code
 
The Art of Clean code
The Art of Clean codeThe Art of Clean code
The Art of Clean code
 
Clean code presentation
Clean code presentationClean code presentation
Clean code presentation
 
7 rules of simple and maintainable code
7 rules of simple and maintainable code7 rules of simple and maintainable code
7 rules of simple and maintainable code
 
C# in depth
C# in depthC# in depth
C# in depth
 
Clean code: understanding Boundaries and Unit Tests
Clean code: understanding Boundaries and Unit TestsClean code: understanding Boundaries and Unit Tests
Clean code: understanding Boundaries and Unit Tests
 

Similar to Clean Code Principles

On Coding Guidelines
On Coding GuidelinesOn Coding Guidelines
On Coding Guidelines
DIlawar Singh
 
Pragmatic Patterns of Ruby on Rails - Ruby Kaigi2009
Pragmatic Patterns of Ruby on Rails - Ruby Kaigi2009Pragmatic Patterns of Ruby on Rails - Ruby Kaigi2009
Pragmatic Patterns of Ruby on Rails - Ruby Kaigi2009Yasuko Ohba
 
Coding standard
Coding standardCoding standard
Coding standard
FAROOK Samath
 
Coding Guidelines in CPP
Coding Guidelines in CPPCoding Guidelines in CPP
Coding Guidelines in CPP
CodeOps Technologies LLP
 
Coding Guidelines - Crafting Clean Code
Coding Guidelines - Crafting Clean CodeCoding Guidelines - Crafting Clean Code
Coding Guidelines - Crafting Clean Code
Ganesh Samarthyam
 
Naming Standards, Clean Code
Naming Standards, Clean CodeNaming Standards, Clean Code
Naming Standards, Clean Code
CleanestCode
 
What's in a name
What's in a nameWhat's in a name
What's in a name
Koby Fruchtnis
 
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
 
Java Basics.pdf
Java Basics.pdfJava Basics.pdf
Java Basics.pdf
EdFeranil
 
Writing Readable Code
Writing Readable CodeWriting Readable Code
Writing Readable Code
eddiehaber
 
Complete C++ programming Language Course
Complete C++ programming Language CourseComplete C++ programming Language Course
Complete C++ programming Language Course
Vivek chan
 
Lecture 01 - Introduction and Review.ppt
Lecture 01 - Introduction and Review.pptLecture 01 - Introduction and Review.ppt
Lecture 01 - Introduction and Review.ppt
MaiGaafar
 
C# 101: Intro to Programming with C#
C# 101: Intro to Programming with C#C# 101: Intro to Programming with C#
C# 101: Intro to Programming with C#
Hawkman Academy
 
Prog1-L2.pptx
Prog1-L2.pptxProg1-L2.pptx
Prog1-L2.pptx
valerie5142000
 
java basics - keywords, statements data types and arrays
java basics - keywords, statements data types and arraysjava basics - keywords, statements data types and arrays
java basics - keywords, statements data types and arrays
mellosuji
 
Crafting high quality code
Crafting high quality code Crafting high quality code
Crafting high quality code
Allan Mangune
 
Clean code & design patterns
Clean code & design patternsClean code & design patterns
Clean code & design patterns
Pascal Larocque
 
Agile_goa_2013_clean_code_tdd
Agile_goa_2013_clean_code_tddAgile_goa_2013_clean_code_tdd
Agile_goa_2013_clean_code_tddSrinivasa GV
 

Similar to Clean Code Principles (20)

Anti-Patterns
Anti-PatternsAnti-Patterns
Anti-Patterns
 
On Coding Guidelines
On Coding GuidelinesOn Coding Guidelines
On Coding Guidelines
 
Pragmatic Patterns of Ruby on Rails - Ruby Kaigi2009
Pragmatic Patterns of Ruby on Rails - Ruby Kaigi2009Pragmatic Patterns of Ruby on Rails - Ruby Kaigi2009
Pragmatic Patterns of Ruby on Rails - Ruby Kaigi2009
 
Coding standard
Coding standardCoding standard
Coding standard
 
Coding Guidelines in CPP
Coding Guidelines in CPPCoding Guidelines in CPP
Coding Guidelines in CPP
 
Coding Guidelines - Crafting Clean Code
Coding Guidelines - Crafting Clean CodeCoding Guidelines - Crafting Clean Code
Coding Guidelines - Crafting Clean Code
 
Naming Standards, Clean Code
Naming Standards, Clean CodeNaming Standards, Clean Code
Naming Standards, Clean Code
 
What's in a name
What's in a nameWhat's in a name
What's in a name
 
Software development best practices & coding guidelines
Software development best practices & coding guidelinesSoftware development best practices & coding guidelines
Software development best practices & coding guidelines
 
Clean code
Clean codeClean code
Clean code
 
Java Basics.pdf
Java Basics.pdfJava Basics.pdf
Java Basics.pdf
 
Writing Readable Code
Writing Readable CodeWriting Readable Code
Writing Readable Code
 
Complete C++ programming Language Course
Complete C++ programming Language CourseComplete C++ programming Language Course
Complete C++ programming Language Course
 
Lecture 01 - Introduction and Review.ppt
Lecture 01 - Introduction and Review.pptLecture 01 - Introduction and Review.ppt
Lecture 01 - Introduction and Review.ppt
 
C# 101: Intro to Programming with C#
C# 101: Intro to Programming with C#C# 101: Intro to Programming with C#
C# 101: Intro to Programming with C#
 
Prog1-L2.pptx
Prog1-L2.pptxProg1-L2.pptx
Prog1-L2.pptx
 
java basics - keywords, statements data types and arrays
java basics - keywords, statements data types and arraysjava basics - keywords, statements data types and arrays
java basics - keywords, statements data types and arrays
 
Crafting high quality code
Crafting high quality code Crafting high quality code
Crafting high quality code
 
Clean code & design patterns
Clean code & design patternsClean code & design patterns
Clean code & design patterns
 
Agile_goa_2013_clean_code_tdd
Agile_goa_2013_clean_code_tddAgile_goa_2013_clean_code_tdd
Agile_goa_2013_clean_code_tdd
 

More from YeurDreamin'

Discover Social Studio: The Product, The Use & The Connector
Discover Social Studio: The Product, The Use & The Connector	Discover Social Studio: The Product, The Use & The Connector
Discover Social Studio: The Product, The Use & The Connector
YeurDreamin'
 
Your Salesforce toolbelt – Practical recommendations to keep your Org healthy
Your Salesforce toolbelt – Practical recommendations to keep your Org healthyYour Salesforce toolbelt – Practical recommendations to keep your Org healthy
Your Salesforce toolbelt – Practical recommendations to keep your Org healthy
YeurDreamin'
 
Admins – You Can Code Too!
Admins – You Can Code Too!Admins – You Can Code Too!
Admins – You Can Code Too!
YeurDreamin'
 
Behind Every Device is a Customer. Learn how to connect IoT devices to Salesf...
Behind Every Device is a Customer. Learn how to connect IoT devices to Salesf...Behind Every Device is a Customer. Learn how to connect IoT devices to Salesf...
Behind Every Device is a Customer. Learn how to connect IoT devices to Salesf...
YeurDreamin'
 
Build Your Own Lightning Community in a Flash - part 2
Build Your Own Lightning Community in a Flash - part 2Build Your Own Lightning Community in a Flash - part 2
Build Your Own Lightning Community in a Flash - part 2
YeurDreamin'
 
Build A Meaningful Network while elevating your Career – Getting the most out...
Build A Meaningful Network while elevating your Career – Getting the most out...Build A Meaningful Network while elevating your Career – Getting the most out...
Build A Meaningful Network while elevating your Career – Getting the most out...
YeurDreamin'
 
From Food Truck Chef to Architect, My Salesforce Journey
From Food Truck Chef to Architect, My Salesforce JourneyFrom Food Truck Chef to Architect, My Salesforce Journey
From Food Truck Chef to Architect, My Salesforce Journey
YeurDreamin'
 
Supercharge your Salesforce with 10 Awesome tips & tricks
Supercharge your Salesforce with 10 Awesome tips & tricksSupercharge your Salesforce with 10 Awesome tips & tricks
Supercharge your Salesforce with 10 Awesome tips & tricks
YeurDreamin'
 
Spectacular Specs and how to write them!
Spectacular Specs and how to write them!Spectacular Specs and how to write them!
Spectacular Specs and how to write them!
YeurDreamin'
 
Set up Continuous Integration using SalesforceDX and Jenkins
Set up Continuous Integration using SalesforceDX and JenkinsSet up Continuous Integration using SalesforceDX and Jenkins
Set up Continuous Integration using SalesforceDX and Jenkins
YeurDreamin'
 
Experience with Salesforce DX on real project
Experience with Salesforce DX on real projectExperience with Salesforce DX on real project
Experience with Salesforce DX on real project
YeurDreamin'
 
Platform Events: How developers and admins work together to implement busines...
Platform Events: How developers and admins work together to implement busines...Platform Events: How developers and admins work together to implement busines...
Platform Events: How developers and admins work together to implement busines...
YeurDreamin'
 
An Admin’s Guide to Workbench
An Admin’s Guide to WorkbenchAn Admin’s Guide to Workbench
An Admin’s Guide to Workbench
YeurDreamin'
 
10 Lessons of Salesforce Nonprofit implementations from a Customer and Integr...
10 Lessons of Salesforce Nonprofit implementations from a Customer and Integr...10 Lessons of Salesforce Nonprofit implementations from a Customer and Integr...
10 Lessons of Salesforce Nonprofit implementations from a Customer and Integr...
YeurDreamin'
 
Top 10 Things Admins Can Learn from Developers (without learning to code)
Top 10 Things Admins Can Learn from Developers (without learning to code)Top 10 Things Admins Can Learn from Developers (without learning to code)
Top 10 Things Admins Can Learn from Developers (without learning to code)
YeurDreamin'
 
How to monitor and prioritize epics of a Service Cloud implementation project...
How to monitor and prioritize epics of a Service Cloud implementation project...How to monitor and prioritize epics of a Service Cloud implementation project...
How to monitor and prioritize epics of a Service Cloud implementation project...
YeurDreamin'
 
Prototyping UX Solutions with Playgrounds and Lightning Web Components
Prototyping UX Solutions with Playgrounds and Lightning Web ComponentsPrototyping UX Solutions with Playgrounds and Lightning Web Components
Prototyping UX Solutions with Playgrounds and Lightning Web Components
YeurDreamin'
 
Want your bank to trust you? You need a credit score. Want your customers to ...
Want your bank to trust you? You need a credit score. Want your customers to ...Want your bank to trust you? You need a credit score. Want your customers to ...
Want your bank to trust you? You need a credit score. Want your customers to ...
YeurDreamin'
 
Invocable methods
Invocable methodsInvocable methods
Invocable methods
YeurDreamin'
 

More from YeurDreamin' (19)

Discover Social Studio: The Product, The Use & The Connector
Discover Social Studio: The Product, The Use & The Connector	Discover Social Studio: The Product, The Use & The Connector
Discover Social Studio: The Product, The Use & The Connector
 
Your Salesforce toolbelt – Practical recommendations to keep your Org healthy
Your Salesforce toolbelt – Practical recommendations to keep your Org healthyYour Salesforce toolbelt – Practical recommendations to keep your Org healthy
Your Salesforce toolbelt – Practical recommendations to keep your Org healthy
 
Admins – You Can Code Too!
Admins – You Can Code Too!Admins – You Can Code Too!
Admins – You Can Code Too!
 
Behind Every Device is a Customer. Learn how to connect IoT devices to Salesf...
Behind Every Device is a Customer. Learn how to connect IoT devices to Salesf...Behind Every Device is a Customer. Learn how to connect IoT devices to Salesf...
Behind Every Device is a Customer. Learn how to connect IoT devices to Salesf...
 
Build Your Own Lightning Community in a Flash - part 2
Build Your Own Lightning Community in a Flash - part 2Build Your Own Lightning Community in a Flash - part 2
Build Your Own Lightning Community in a Flash - part 2
 
Build A Meaningful Network while elevating your Career – Getting the most out...
Build A Meaningful Network while elevating your Career – Getting the most out...Build A Meaningful Network while elevating your Career – Getting the most out...
Build A Meaningful Network while elevating your Career – Getting the most out...
 
From Food Truck Chef to Architect, My Salesforce Journey
From Food Truck Chef to Architect, My Salesforce JourneyFrom Food Truck Chef to Architect, My Salesforce Journey
From Food Truck Chef to Architect, My Salesforce Journey
 
Supercharge your Salesforce with 10 Awesome tips & tricks
Supercharge your Salesforce with 10 Awesome tips & tricksSupercharge your Salesforce with 10 Awesome tips & tricks
Supercharge your Salesforce with 10 Awesome tips & tricks
 
Spectacular Specs and how to write them!
Spectacular Specs and how to write them!Spectacular Specs and how to write them!
Spectacular Specs and how to write them!
 
Set up Continuous Integration using SalesforceDX and Jenkins
Set up Continuous Integration using SalesforceDX and JenkinsSet up Continuous Integration using SalesforceDX and Jenkins
Set up Continuous Integration using SalesforceDX and Jenkins
 
Experience with Salesforce DX on real project
Experience with Salesforce DX on real projectExperience with Salesforce DX on real project
Experience with Salesforce DX on real project
 
Platform Events: How developers and admins work together to implement busines...
Platform Events: How developers and admins work together to implement busines...Platform Events: How developers and admins work together to implement busines...
Platform Events: How developers and admins work together to implement busines...
 
An Admin’s Guide to Workbench
An Admin’s Guide to WorkbenchAn Admin’s Guide to Workbench
An Admin’s Guide to Workbench
 
10 Lessons of Salesforce Nonprofit implementations from a Customer and Integr...
10 Lessons of Salesforce Nonprofit implementations from a Customer and Integr...10 Lessons of Salesforce Nonprofit implementations from a Customer and Integr...
10 Lessons of Salesforce Nonprofit implementations from a Customer and Integr...
 
Top 10 Things Admins Can Learn from Developers (without learning to code)
Top 10 Things Admins Can Learn from Developers (without learning to code)Top 10 Things Admins Can Learn from Developers (without learning to code)
Top 10 Things Admins Can Learn from Developers (without learning to code)
 
How to monitor and prioritize epics of a Service Cloud implementation project...
How to monitor and prioritize epics of a Service Cloud implementation project...How to monitor and prioritize epics of a Service Cloud implementation project...
How to monitor and prioritize epics of a Service Cloud implementation project...
 
Prototyping UX Solutions with Playgrounds and Lightning Web Components
Prototyping UX Solutions with Playgrounds and Lightning Web ComponentsPrototyping UX Solutions with Playgrounds and Lightning Web Components
Prototyping UX Solutions with Playgrounds and Lightning Web Components
 
Want your bank to trust you? You need a credit score. Want your customers to ...
Want your bank to trust you? You need a credit score. Want your customers to ...Want your bank to trust you? You need a credit score. Want your customers to ...
Want your bank to trust you? You need a credit score. Want your customers to ...
 
Invocable methods
Invocable methodsInvocable methods
Invocable methods
 

Recently uploaded

Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"
Donna Lenk
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
Safe Software
 
Graphic Design Crash Course for beginners
Graphic Design Crash Course for beginnersGraphic Design Crash Course for beginners
Graphic Design Crash Course for beginners
e20449
 
Text-Summarization-of-Breaking-News-Using-Fine-tuning-BART-Model.pptx
Text-Summarization-of-Breaking-News-Using-Fine-tuning-BART-Model.pptxText-Summarization-of-Breaking-News-Using-Fine-tuning-BART-Model.pptx
Text-Summarization-of-Breaking-News-Using-Fine-tuning-BART-Model.pptx
ShamsuddeenMuhammadA
 
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus
 
First Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User EndpointsFirst Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User Endpoints
Globus
 
Understanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSageUnderstanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSage
Globus
 
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisProviding Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Globus
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke
 
Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024
Globus
 
2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx
Georgi Kodinov
 
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Shahin Sheidaei
 
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns
 
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Globus
 
How to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good PracticesHow to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good Practices
Globus
 
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Globus
 
Launch Your Streaming Platforms in Minutes
Launch Your Streaming Platforms in MinutesLaunch Your Streaming Platforms in Minutes
Launch Your Streaming Platforms in Minutes
Roshan Dwivedi
 
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Globus
 
Vitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdfVitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke
 
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket ManagementUtilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate
 

Recently uploaded (20)

Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
 
Graphic Design Crash Course for beginners
Graphic Design Crash Course for beginnersGraphic Design Crash Course for beginners
Graphic Design Crash Course for beginners
 
Text-Summarization-of-Breaking-News-Using-Fine-tuning-BART-Model.pptx
Text-Summarization-of-Breaking-News-Using-Fine-tuning-BART-Model.pptxText-Summarization-of-Breaking-News-Using-Fine-tuning-BART-Model.pptx
Text-Summarization-of-Breaking-News-Using-Fine-tuning-BART-Model.pptx
 
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024
 
First Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User EndpointsFirst Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User Endpoints
 
Understanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSageUnderstanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSage
 
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisProviding Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
 
Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024
 
2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx
 
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
 
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology Solutions
 
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
 
How to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good PracticesHow to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good Practices
 
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
 
Launch Your Streaming Platforms in Minutes
Launch Your Streaming Platforms in MinutesLaunch Your Streaming Platforms in Minutes
Launch Your Streaming Platforms in Minutes
 
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
 
Vitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdfVitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdf
 
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket ManagementUtilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
 

Clean Code Principles

  • 2. #YeurDreamin2019 About me • Salesforce Platform Developer • Hanging out in the cloud since 2014 • Big and small projects • Currently based in Berlin (SumUp) Vladimir Romanov
  • 4. #YeurDreamin2019 WHAT IS CLEAN CODE? • Human Readable • Easy to change and maintain
  • 6. #YeurDreamin2019 CLEAN CODE PRINCIPLES 0. The Boy Scout rule 1. Meaningful Naming 2. Constants instead of Hard-Coded Strings or Integers 3. Small Functions
  • 7. #YeurDreamin2019 BOY SCOUT RULE • Always leave the campground cleaner than you found it. (Boy Scouts) • Always leave the code you’re editing a little better than you found it. (Robert C. Martin)  Take responsibility of the environment  There is no ideal code – there is better code =
  • 8. #YeurDreamin2019 #1 MEANINGFUL NAMING • Descriptive, Intention-Revealing • Use words, not abbreviations  Better long than ambiguous • Searchable a -> accountRecord genymdhms -> generationTimestamp
  • 9. #YeurDreamin2019 Slide title • First level 1  Second level 2
  • 10. #YeurDreamin2019 Descriptive Names • Class Names  Noun or noun phrase like Customer, WikiPage  Avoid generic words like Manager, Processor, Data, Info • Method Names Should Say What They Do  verb or verb phrase names like postPayment, deletePage, or save.  doRename() -> renamePage(), renamePageAndOptionallyAllReferences()
  • 11. #YeurDreamin2019 Naming considerations • Having variable type as part of name  Account parentAccount;  Button resetButton; • Using plural names for arrays/collections of objects  List or Set can be omitted if sets usually contain unique primitive type values and lists contain non-unique complex objects  userList -> users  List<FollowUp__c> followUps;  Set<Id> accountIds;
  • 12. #YeurDreamin2019 Naming considerations • Define and follow a Naming convention per project, for example:  Use CamelCase (sendSMS -> sendSms)  Variable and method names start with lowercase letter (accountRecord, accounts)  Class names start with uppercase letter (Account)  Constants written in uppercase separated with underscore (DAYS_IN_WEEK, SOBJECTTYPE_CASE, STR_OK)
  • 13. #YeurDreamin2019 Naming considerations • Re-evaluate names as software evolves • Respect Encapsulation  Add public access or {get;set;} only when necessary. Use private variables by default.  Private variables are easier to change – they are referenced only inside the class
  • 14. #YeurDreamin2019 Naming considerations • Use variables as a way to say more about what the code is doing • Break the calculations up into intermediate values that are held in variables with meaningful names. Matcher match = headerPattern.matcher(line); if(match.find()) { String key = match.group(1); String value = match.group(2); headers.put(key.toLowerCase(), value); }
  • 15. #YeurDreamin2019 #2 CONSTANTS INSTEAD OF HARD-CODED STRINGS OR INTEGERS • Use constant variables instead of hardcoded Strings or Numbers  DAYS_IN_WEEK instead of 7  COMPANY_CODE_ITALY instead of ‘485’ • Give them a descriptive name using UPPER CASE • Define all the constants at the top of the class • Consider using a class to contain global constants. • Consider getting value for constants from Custom Labels or Custom Metadata • Easier to  Read  Search  Change value  Test
  • 16. #YeurDreamin2019 #3 SMALL FUNCTIONS • Use Small Functions – split a larger function into smaller ones by looking at  logical sections  levels of indentation  Rule of thumb - Every Function should do One thing and do it well  Does one thing  Separates levels of abstraction  Easier to  Understand  Modify  Reuse, reduce duplication  Test • The less arguments the better (ideally <= 2)  Use instance / static variables to pass frequently used data  Use DTO classes to encapsulate parameters – e.g. InitDataDto, AddressWrapper, RequestWrapper
  • 17. #YeurDreamin2019 Applying the principles - Clean Conditionals • Encapsulate conditionals  if (timer.hasExpired() && !timer.isRecurrent()) -> if (shouldBeDeleted(timer)) • Encapsulate boundary conditionals  level + 1 < tags.length -> if(nextLevel < tags.length) • Avoid Negative Conditionals  if ( !followUpNeeded() ) -> if ( followUpNotNeeded() ) • Use standard apex methods for null checks and empty lists checks  myString != null && myString!=‘’ -> String.isNotEmpty(myString)  myList.size()==0 -> myList.isEmpty()  $A.util.isEmpty(value) – in Lightning components
  • 18. #YeurDreamin2019 Applying the principles - Clean SOQL • Format SOQL queries • Use a separate function for each SOQL query, adding all fields on separate lines in the alphabetical order • Place the function at the end of class or use a Data Access Layer class to reuse queries  allows to reuse it  Easier to add fields  Better maintenance private static List<Account> retrieveAccountsByIds (Set<Id> accountIds) { return [ SELECT Id, Name FROM Account WHERE Id IN :accountIds ]; }
  • 19. #YeurDreamin2019 Applying the principles - Clean Loops and Branches • Keep indentation at max 2 levels • an if else chain inside a function may mean it is doing more than one thing • Too many branch levels may mean working on different levels of abstraction, which makes harder to read and easier to miss something • Use loop control statements like break; and continue; statements to reduce indentation for (WRP_Email emailWrapper : emailWrappers) { if (emailWrapper.hasPropertyRequest()) { Id plotId = getPlotIdFromEmail(emailWrapper); if (plotId!= null) plotIds.add(plotId); } } -> for (WRP_Email emailWrapper : emailWrappers) { if (emailWrapper.hasNoPropertyRequest()) continue; Id plotId = getPlotIdFromEmail(emailWrapper); if (plotId!= null) plotIds.add(plotId); }
  • 20. #YeurDreamin2019 Applying the principles - Clean comments • Clean code often doesn’t need comments!  Don’t use trivial/redundant comments  Delete outdated comments when software evolves (saving them in git repository)
  • 21. #YeurDreamin2019 Applying the principles - Clean debugging • Write class name and method name in debug message  System.debug(‘MyClass::myFunction()::myVariable: ’+myVariable);  No need to add the message when names reveal the intention of the class, function and the variable.  Easier to search in debug log  Works best when functions are small
  • 22. SHOW ME MORE CODE!
  • 23. #YeurDreamin2019 CHANGE OF VISION • By applying the Clean Code Principles you can See how you can improve the code and you can do it as you go!
  • 24. #YeurDreamin2019 Further reading and watching • Book - Clean Code (Robert C. Martin)  https://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882 • Pluralsight courses:  Clean Code: Writing Code for Humans (Cory House)  https://app.pluralsight.com/library/courses/writing-clean-code-humans  Maximize Your Value through Salesforce Coding Best Practices (Matt Kaufman and Don Robins)  https://app.pluralsight.com/library/courses/play-by-play-maximize-value-through-salesforce-coding-best- practices/table-of-contents
  • 25. CODE REVIEW CHALLENGE! • Make groups of 2-3 people • Set date and time when you will do a code review together • Bring some of your code • Discuss what contributes to readability and maintainability
  • 26. #YeurDreamin2019 Join us for drinks @18:00 sponsored by Community sponsors: Stay in touch! • LinkedIn https://www.linkedin.com/in/vladimir-romanov/ • Twitter @vladfromrome • YeurDreamin Slack #clean-code NonProfit-track sponsor:

Editor's Notes

  1. Programming is the art of telling another human what one wants the computer to do. Donald Knuth
  2. It would take much longer to cook eggs and bacon here…
  3. Human brain is able to keep in mind only 7 things at a time