SlideShare a Scribd company logo
1 of 32
Download to read offline
Qualities of clean code
With Applications in Javascript
Agenda
● Qualities of clean code
● Tools to ensure code styles (in Js)
● Hints to write Testable code
● Pure functions
● Useful functional programming
helpers
● Use JS Modules (AMD / CommonJs)
"Any fool can write code that a computer can
understand.Good programmers write code that
humans can understand."
-Martin Fowler
Qualities of clean code
● Naming
● Functions
● Comments
● AESTHETICS
Qualities of clean code -Naming
‘There are only two hard things in Computer
Science: cache invalidation and naming things.’
- Phil Karlton
Qualities of clean code -Naming
● Choosing specific words
● Using concrete names
● Deciding how long a name should be
● Using name formatting to pack extra information
Qualities of clean code -Naming (Choosing specific words)
● “get” is very unspecific def GetPage(url)
○ get a page from a local cache?
○ from a database?
○ from the Internet?
If it’s from the Internet, a more specific name might be FetchPage()
● Avoid Generic Names Like tmp and retval
● Names like i, j, iter, and it are commonly used as indices and loop iterators
Qualities of clean code -Naming (Choosing specific words)
Qualities of clean code -Naming (Using concrete names)
● Values with Units
var start = (new Date()).getTime()
var start_ms = (new Date()).getTime();
● Encoding Other Important Attributes
Qualities of clean code -Naming (how long a name should be)
● Shorter Names Are Okay for Shorter Scope
● TextMate ESC Acronyms and Abbreviations
○ i.e. naming a class BEManager instead of BackEndManager.
● Throwing Out Unneeded Words
○ ConvertToString(), ToString()
Qualities of clean code -Naming (name formatting to pack
extra information)
var x = new DatePicker(); // DatePicker() is a "constructor" function
var y = pageHeight(); // pageHeight() is an ordinary function
var $all_images = $("img"); // $all_images is a jQuery object
var height = 250; // height is not
<div id="middle_column" class="main-content">
Functions
● The smaller the better
● A function should only do one thing (KISS)
● No nested control structure
● Less arguments are better
Comments
● Comments are a code smell
● Comments are not subtitles
● Comments are not an art project
● Comments are not source control
Aesthetics
It’s “formatting” your code in a consistent, meaningful way,
you make it easier and faster to read
Aesthetics
● Organize Declarations into Blocks
Aesthetics
● Aligning parts of the code into “columns” can make
code easy to skim through.
Aesthetics
● Use empty lines to break apart large blocks into logical
“paragraphs.
Tools to ensure code styles (in Js)
● JSCS(.jscsrc)
● ESLint (.eslintrc.json) Eslint
● .jsbeautifyrc
Coding_Style
Hints to write Testable code
● Keep Business Logic and Display Logic Separate
● Avoid Side Effects
● Give Each Function a Single Purpose
● Don’t Mutate Parameters
● Use Dependency Injection
● Write Your Tests Before Your Code
Hints to write Testable code
● Keep Business Logic and Display Logic Separate
Hints to write Testable code
● Avoid Side Effects
Hints to write Testable code
● Use Dependency Injection
Hints to write Testable code
● Don’t Mutate Parameters
Pure Functions
A pure function is a function which:
● Given the same input, will always return the same output.
● Produces no side effects.
● Relies on no external mutable state.
pure-functions-javascript
Useful functional programming helpers (map,filter,reduce)
● Functional techniques can help you write more
declarative code that is easier to understand at a
glance, refactor, and test.
● One of the cornerstones of functional programming is its
special use of lists and list operations.
● These are natively available in any recent browser and
in Node.js
Useful functional programming helpers -map
Think of map as a "for each" loop, that is specifically for
transforming values - one input value corresponds to one
'transformed' output value.
Useful functional programming helpers -filter
The filter() method creates a new array with all elements
that pass the test implemented by the provided function
Useful functional programming helpers -reduce
The reduce() method applies a function against an accumulator and each value
of the array (from left-to-right) to reduce it to a single value.
Use JS Modules (AMD / CommonJs)
● AMD (Asynchronous Module Definition)
Use JS Modules (AMD / CommonJs)
● CommonJS
Use JS Modules (AMD / CommonJs)
● CommonJS
References
● Art of Readable Code
● https://www.toptal.com/javascript/writing-testable-code-in-javascript
● master-the-javascript-interview-what-is-a-pure-function

More Related Content

What's hot

Datatype in JavaScript
Datatype in JavaScriptDatatype in JavaScript
Datatype in JavaScriptRajat Saxena
 
Functional programming
Functional programmingFunctional programming
Functional programmingijcd
 
JavaScript Object Oriented Programming Cheat Sheet
JavaScript Object Oriented Programming Cheat SheetJavaScript Object Oriented Programming Cheat Sheet
JavaScript Object Oriented Programming Cheat SheetHDR1001
 
C sharp fundamentals Part I
C sharp fundamentals Part IC sharp fundamentals Part I
C sharp fundamentals Part IDevMix
 
Introduction to Object Oriented Javascript
Introduction to Object Oriented JavascriptIntroduction to Object Oriented Javascript
Introduction to Object Oriented Javascriptnodeninjas
 
Brutal refactoring, lying code, the Churn, and other emotional stories from L...
Brutal refactoring, lying code, the Churn, and other emotional stories from L...Brutal refactoring, lying code, the Churn, and other emotional stories from L...
Brutal refactoring, lying code, the Churn, and other emotional stories from L...Matthias Noback
 
GeekNight 22.0 Multi-paradigm programming in Scala and Akka
GeekNight 22.0 Multi-paradigm programming in Scala and AkkaGeekNight 22.0 Multi-paradigm programming in Scala and Akka
GeekNight 22.0 Multi-paradigm programming in Scala and AkkaGeekNightHyderabad
 
Functional programming with Xtend
Functional programming with XtendFunctional programming with Xtend
Functional programming with XtendSven Efftinge
 

What's hot (20)

JavaScript Variables
JavaScript VariablesJavaScript Variables
JavaScript Variables
 
Datatype in JavaScript
Datatype in JavaScriptDatatype in JavaScript
Datatype in JavaScript
 
Functional programming
Functional programmingFunctional programming
Functional programming
 
JavaScript Object Oriented Programming Cheat Sheet
JavaScript Object Oriented Programming Cheat SheetJavaScript Object Oriented Programming Cheat Sheet
JavaScript Object Oriented Programming Cheat Sheet
 
Learn JavaScript From Scratch
Learn JavaScript From ScratchLearn JavaScript From Scratch
Learn JavaScript From Scratch
 
C sharp fundamentals Part I
C sharp fundamentals Part IC sharp fundamentals Part I
C sharp fundamentals Part I
 
Introduction to Object Oriented Javascript
Introduction to Object Oriented JavascriptIntroduction to Object Oriented Javascript
Introduction to Object Oriented Javascript
 
jQuery Beginner
jQuery BeginnerjQuery Beginner
jQuery Beginner
 
Effective PHP. Part 5
Effective PHP. Part 5Effective PHP. Part 5
Effective PHP. Part 5
 
Brutal refactoring, lying code, the Churn, and other emotional stories from L...
Brutal refactoring, lying code, the Churn, and other emotional stories from L...Brutal refactoring, lying code, the Churn, and other emotional stories from L...
Brutal refactoring, lying code, the Churn, and other emotional stories from L...
 
Practical domain driven design
Practical domain driven designPractical domain driven design
Practical domain driven design
 
Effective PHP. Part 4
Effective PHP. Part 4Effective PHP. Part 4
Effective PHP. Part 4
 
CLEAN CODE
CLEAN CODECLEAN CODE
CLEAN CODE
 
GeekNight 22.0 Multi-paradigm programming in Scala and Akka
GeekNight 22.0 Multi-paradigm programming in Scala and AkkaGeekNight 22.0 Multi-paradigm programming in Scala and Akka
GeekNight 22.0 Multi-paradigm programming in Scala and Akka
 
Functional programming with Xtend
Functional programming with XtendFunctional programming with Xtend
Functional programming with Xtend
 
Introduction to Advanced Javascript
Introduction to Advanced JavascriptIntroduction to Advanced Javascript
Introduction to Advanced Javascript
 
Xtext Webinar
Xtext WebinarXtext Webinar
Xtext Webinar
 
Introduction to Functional programming
Introduction to Functional programmingIntroduction to Functional programming
Introduction to Functional programming
 
Road to code
Road to codeRoad to code
Road to code
 
Learn TypeScript from scratch
Learn TypeScript from scratchLearn TypeScript from scratch
Learn TypeScript from scratch
 

Similar to Sharable of qualities of clean code

Structured web programming
Structured web programmingStructured web programming
Structured web programmingahfast
 
Productivity Enhencement with Visual Studio
Productivity Enhencement with Visual StudioProductivity Enhencement with Visual Studio
Productivity Enhencement with Visual StudioAhasan Habib
 
Keeping business logic out of your UIs
Keeping business logic out of your UIsKeeping business logic out of your UIs
Keeping business logic out of your UIsPetter Holmström
 
Understanding Implicits in Scala
Understanding Implicits in ScalaUnderstanding Implicits in Scala
Understanding Implicits in Scaladatamantra
 
Robust C++ Task Systems Through Compile-time Checks
Robust C++ Task Systems Through Compile-time ChecksRobust C++ Task Systems Through Compile-time Checks
Robust C++ Task Systems Through Compile-time ChecksStoyan Nikolov
 
Dart the Better JavaScript
Dart the Better JavaScriptDart the Better JavaScript
Dart the Better JavaScriptJorg Janke
 
Practical C++ Generative Programming
Practical C++ Generative ProgrammingPractical C++ Generative Programming
Practical C++ Generative ProgrammingSchalk Cronjé
 
Functional Programming 101 for Java 7 Developers
Functional Programming 101 for Java 7 DevelopersFunctional Programming 101 for Java 7 Developers
Functional Programming 101 for Java 7 DevelopersJayaram Sankaranarayanan
 
Go Is Your Next Language — Sergii Shapoval
Go Is Your Next Language — Sergii ShapovalGo Is Your Next Language — Sergii Shapoval
Go Is Your Next Language — Sergii ShapovalGlobalLogic Ukraine
 
Clean code and refactoring
Clean code and refactoringClean code and refactoring
Clean code and refactoringYuriy Gerasimov
 
Andriy Shalaenko - GO security tips
Andriy Shalaenko - GO security tipsAndriy Shalaenko - GO security tips
Andriy Shalaenko - GO security tipsOWASP Kyiv
 
Framework engineering JCO 2011
Framework engineering JCO 2011Framework engineering JCO 2011
Framework engineering JCO 2011YoungSu Son
 
Keeping code clean
Keeping code cleanKeeping code clean
Keeping code cleanBrett Child
 
Not Your Fathers C - C Application Development In 2016
Not Your Fathers C - C Application Development In 2016Not Your Fathers C - C Application Development In 2016
Not Your Fathers C - C Application Development In 2016maiktoepfer
 
Design patterns for fun and profit
Design patterns for fun and profitDesign patterns for fun and profit
Design patterns for fun and profitNikolas Vourlakis
 
IDE and Toolset For Magento Development
IDE and Toolset For Magento DevelopmentIDE and Toolset For Magento Development
IDE and Toolset For Magento DevelopmentAbid Malik
 
5 hs mpostcustomizationrenefonseca
5 hs mpostcustomizationrenefonseca5 hs mpostcustomizationrenefonseca
5 hs mpostcustomizationrenefonsecassuserfadb24
 

Similar to Sharable of qualities of clean code (20)

Structured web programming
Structured web programmingStructured web programming
Structured web programming
 
Productivity Enhencement with Visual Studio
Productivity Enhencement with Visual StudioProductivity Enhencement with Visual Studio
Productivity Enhencement with Visual Studio
 
Keeping business logic out of your UIs
Keeping business logic out of your UIsKeeping business logic out of your UIs
Keeping business logic out of your UIs
 
Understanding Implicits in Scala
Understanding Implicits in ScalaUnderstanding Implicits in Scala
Understanding Implicits in Scala
 
Robust C++ Task Systems Through Compile-time Checks
Robust C++ Task Systems Through Compile-time ChecksRobust C++ Task Systems Through Compile-time Checks
Robust C++ Task Systems Through Compile-time Checks
 
Dart the Better JavaScript
Dart the Better JavaScriptDart the Better JavaScript
Dart the Better JavaScript
 
Practical C++ Generative Programming
Practical C++ Generative ProgrammingPractical C++ Generative Programming
Practical C++ Generative Programming
 
Functional Programming 101 for Java 7 Developers
Functional Programming 101 for Java 7 DevelopersFunctional Programming 101 for Java 7 Developers
Functional Programming 101 for Java 7 Developers
 
Go Is Your Next Language — Sergii Shapoval
Go Is Your Next Language — Sergii ShapovalGo Is Your Next Language — Sergii Shapoval
Go Is Your Next Language — Sergii Shapoval
 
AngularJS Workshop
AngularJS WorkshopAngularJS Workshop
AngularJS Workshop
 
Clean code and refactoring
Clean code and refactoringClean code and refactoring
Clean code and refactoring
 
Andriy Shalaenko - GO security tips
Andriy Shalaenko - GO security tipsAndriy Shalaenko - GO security tips
Andriy Shalaenko - GO security tips
 
Framework engineering JCO 2011
Framework engineering JCO 2011Framework engineering JCO 2011
Framework engineering JCO 2011
 
Wt unit 2 ppts client sied technology
Wt unit 2 ppts client sied technologyWt unit 2 ppts client sied technology
Wt unit 2 ppts client sied technology
 
Wt unit 2 ppts client side technology
Wt unit 2 ppts client side technologyWt unit 2 ppts client side technology
Wt unit 2 ppts client side technology
 
Keeping code clean
Keeping code cleanKeeping code clean
Keeping code clean
 
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
 
Design patterns for fun and profit
Design patterns for fun and profitDesign patterns for fun and profit
Design patterns for fun and profit
 
IDE and Toolset For Magento Development
IDE and Toolset For Magento DevelopmentIDE and Toolset For Magento Development
IDE and Toolset For Magento Development
 
5 hs mpostcustomizationrenefonseca
5 hs mpostcustomizationrenefonseca5 hs mpostcustomizationrenefonseca
5 hs mpostcustomizationrenefonseca
 

Recently uploaded

ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - InfographicHr365.us smith
 
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝soniya singh
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about usDynamic Netsoft
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyFrank van der Linden
 
cybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningcybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningVitsRangannavar
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 

Recently uploaded (20)

ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - Infographic
 
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about us
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The Ugly
 
cybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningcybersecurity notes for mca students for learning
cybersecurity notes for mca students for learning
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 

Sharable of qualities of clean code

  • 1. Qualities of clean code With Applications in Javascript
  • 2. Agenda ● Qualities of clean code ● Tools to ensure code styles (in Js) ● Hints to write Testable code ● Pure functions ● Useful functional programming helpers ● Use JS Modules (AMD / CommonJs)
  • 3. "Any fool can write code that a computer can understand.Good programmers write code that humans can understand." -Martin Fowler
  • 4. Qualities of clean code ● Naming ● Functions ● Comments ● AESTHETICS
  • 5. Qualities of clean code -Naming ‘There are only two hard things in Computer Science: cache invalidation and naming things.’ - Phil Karlton
  • 6. Qualities of clean code -Naming ● Choosing specific words ● Using concrete names ● Deciding how long a name should be ● Using name formatting to pack extra information
  • 7. Qualities of clean code -Naming (Choosing specific words) ● “get” is very unspecific def GetPage(url) ○ get a page from a local cache? ○ from a database? ○ from the Internet? If it’s from the Internet, a more specific name might be FetchPage() ● Avoid Generic Names Like tmp and retval ● Names like i, j, iter, and it are commonly used as indices and loop iterators
  • 8. Qualities of clean code -Naming (Choosing specific words)
  • 9. Qualities of clean code -Naming (Using concrete names) ● Values with Units var start = (new Date()).getTime() var start_ms = (new Date()).getTime(); ● Encoding Other Important Attributes
  • 10. Qualities of clean code -Naming (how long a name should be) ● Shorter Names Are Okay for Shorter Scope ● TextMate ESC Acronyms and Abbreviations ○ i.e. naming a class BEManager instead of BackEndManager. ● Throwing Out Unneeded Words ○ ConvertToString(), ToString()
  • 11. Qualities of clean code -Naming (name formatting to pack extra information) var x = new DatePicker(); // DatePicker() is a "constructor" function var y = pageHeight(); // pageHeight() is an ordinary function var $all_images = $("img"); // $all_images is a jQuery object var height = 250; // height is not <div id="middle_column" class="main-content">
  • 12. Functions ● The smaller the better ● A function should only do one thing (KISS) ● No nested control structure ● Less arguments are better
  • 13. Comments ● Comments are a code smell ● Comments are not subtitles ● Comments are not an art project ● Comments are not source control
  • 14. Aesthetics It’s “formatting” your code in a consistent, meaningful way, you make it easier and faster to read
  • 16. Aesthetics ● Aligning parts of the code into “columns” can make code easy to skim through.
  • 17. Aesthetics ● Use empty lines to break apart large blocks into logical “paragraphs.
  • 18. Tools to ensure code styles (in Js) ● JSCS(.jscsrc) ● ESLint (.eslintrc.json) Eslint ● .jsbeautifyrc Coding_Style
  • 19. Hints to write Testable code ● Keep Business Logic and Display Logic Separate ● Avoid Side Effects ● Give Each Function a Single Purpose ● Don’t Mutate Parameters ● Use Dependency Injection ● Write Your Tests Before Your Code
  • 20. Hints to write Testable code ● Keep Business Logic and Display Logic Separate
  • 21. Hints to write Testable code ● Avoid Side Effects
  • 22. Hints to write Testable code ● Use Dependency Injection
  • 23. Hints to write Testable code ● Don’t Mutate Parameters
  • 24. Pure Functions A pure function is a function which: ● Given the same input, will always return the same output. ● Produces no side effects. ● Relies on no external mutable state. pure-functions-javascript
  • 25. Useful functional programming helpers (map,filter,reduce) ● Functional techniques can help you write more declarative code that is easier to understand at a glance, refactor, and test. ● One of the cornerstones of functional programming is its special use of lists and list operations. ● These are natively available in any recent browser and in Node.js
  • 26. Useful functional programming helpers -map Think of map as a "for each" loop, that is specifically for transforming values - one input value corresponds to one 'transformed' output value.
  • 27. Useful functional programming helpers -filter The filter() method creates a new array with all elements that pass the test implemented by the provided function
  • 28. Useful functional programming helpers -reduce The reduce() method applies a function against an accumulator and each value of the array (from left-to-right) to reduce it to a single value.
  • 29. Use JS Modules (AMD / CommonJs) ● AMD (Asynchronous Module Definition)
  • 30. Use JS Modules (AMD / CommonJs) ● CommonJS
  • 31. Use JS Modules (AMD / CommonJs) ● CommonJS
  • 32. References ● Art of Readable Code ● https://www.toptal.com/javascript/writing-testable-code-in-javascript ● master-the-javascript-interview-what-is-a-pure-function