SlideShare a Scribd company logo
Clean and Typechecked JS
Arthur Reis Puthin
About me
Developer at ilegra (think beyond!)
Mostly front-end stuff
Undergraduate at Unisinos
/aputhin
Para enviar uma pergunta e receber
o material desta apresentação acesse:
bit.ly/arthurtdc
JS is nuts
Let's fix it where we
are best at: the code
"The most often-cited rationales for
type systems are that they:
1. Catch errors early
2. Improve readability of code
3. Facilitate tooling
4. Improve runtime performance"
http://www.hammerlab.org/2015/12/09/our-experiences-with-flow/
"The results are encouraging; we
found that using Flow or TypeScript
could have prevented 15% of the
public bugs for public projects on
GitHub."
http://ttendency.cs.ucl.ac.uk/projects/type_study/
Pick your poison:
➔ Supersets (i.e. TypeScript or JavaScript++)
➔ Static Typecheckers (i.e. Flow)
➔ Compile to JS (i.e. Elm or PureScript)
Meet Flow.
https://flow.org/
How does it work?
// @flow
function sqr(n: number): number {
return n * n;
}
sqr("2"); // Error!
// setup babel to clean it up
// install the binary
npm install --save-dev flow-bin
// add it to package.json
"scripts": {"flow": "flow"}
// run to check for errors
npm run flow init
npm run flow
npm run flow stop
Type Annotation Basics
let isOpen: boolean = true;
const answer: number = 42; // includes Infinity and NaN
let company: string = 'ilegra';
const hope: null = null;
let theQuestion: void = undefined; // uncompatible with null!
const words: Array<string> = ['I', 'am', 'groot']; // Array<T>
let iCanBeAnything: any = 'es' + 2016; // wildcard, DON'T USE IT
// "Using any is completely unsafe, and should be avoided whenever
possible" - https://flow.org/en/docs/types/any/
Object & Function Typing
let proplessObject: Object = {}; // works, but loses typechecking goodness
const identity: { name: string, age: number } = {
name: 'Arthur',
age: 26,
};
let booksPageCounts: { [name: string]: number } = {
Javascript: 999,
JSGoodParts: 100,
};
const calculateArea = (radius: number): number => { // return type is optional
return 3.14 * radius * radius;
};
Type Alias
type Address = {
street: string,
number: number
};
let myWorkAdress: Address = {
street: 'Washington Luiz',
number: 820,
};
type Email = string; // aliasing
var myEmail: Email = 'arthur.rprp@gmail.com';
Generics, Maybe and Optionals
type Password<T> = { key: T };
let numberKey: Password<number> = { key: 12345678 };
let stringKey: Password<string> = { key: "shhhhh" };
let arrayKey: Password<Array<number>> = { key: [4, 2] }
var message: ?string = null; // accepts string, null or undefined
function acceptsOptString(value?: string) {} // accepts string or undefined
Literals & Union
function getColor(name: "success" | "warning" | "danger") {
// ...
}
getColor("success"); // Works!
getColor("danger"); // Works!
getColor("error"); // Error!
// accepts any number, boolean or string
function toStringPrimitives(value: number | boolean | string) {
return String(value);
}
Meet Flow.
https://flow.org/
Types: ✓
But we have to go further...
“It is not the language that makes
programs appear simple. It is the
programmer that make the language
appear simple!”
Robert C. Martin, Clean Code: A Handbook of Agile Software Craftsmanship
Keep an eye for
code smells...
Code Smells:
Non-strict Equality
// All of these evaluate to 'true'
console.log(false == '0');
console.log(null == undefined);
console.log(" trn" == 0);
console.log('' == 0);
console.log(0 == '0');
if ({}) {...}
if ([]) {...}
// Always go for strict equality/inequality
console.log(0 === '0'); // false
// random gotcha: NaN comparison
console.log(NaN == NaN); // false
console.log(NaN === NaN); // false
console.log(isNaN(NaN)); // true, but beware
console.log(NaN != NaN); // true
Code Smells:
Incorrect context
Game.prototype.restart = function () {
this.clearLocalStorage();
this.timer = setTimeout(function() {
this.clearBoard(); // what is "this"?
}, 0);
};
// Solution 1: explicit binding with .bind()
let clearInTime = function() {
this.clearBoard();
};
this.clearInTime = clearInTime.bind(this);
// Solution 2: arrow functions
this.clearInTime = setTimeout(() => {
this.clearBoard();
}, 0);
Code Smells:
Variable scoping
and handling
for (var i = 0; i < 10; i++) {
elements[i].onclick = function() {
console.log("This is element #" + i); // 10
};
}
console.log(i); // = 10; i "leaks" out of scope
// solution: let (ES6) is block-level scoped
function () {
var a = 1;
let b = 2;
}
console.log(a); // 1
console.log(b); // undefined
/* const is NOT for scope hoisting: it is for
read-only/immutable values! */
Code Smells:
Anonymous
Functions
// debugging this stack trace might go awry...
document.querySelector('button')
.addEventListener('input', function(e) {
// ...
});
// naming favors stack-tracing and code reuse
const kaboom = function() { alert('Ka-boom') };
document.querySelector('button')
.addEventListener('click', kaboom);
document.querySelector('#egg')
.addEventListener('mouseenter', kaboom);
More Anti-patterns to keep in mind...
- Too many global namespace variables
- Too much direct DOM manipulation
- Modifying the Object class prototype (or any prototype for that matter…)
JS Clean Code:
Fewer Arguments
// BAD
function createMenu(title, body, buttonText,
cancellable) {...}
// GOOD
function createMenu({ title, body, buttonText,
cancellable }) {...}
createMenu({
title: 'Foo',
body: 'Bar',
buttonText: 'Baz',
cancellable: true
});
src: github.com/ryanmcdermott/clean-code-javascript
JS Clean Code:
Avoid Side Effects
src: github.com/ryanmcdermott/clean-code-javascript
function splitIntoFirstAndLastName(name) {
return name.split(' ');
}
const name = 'Ryan McDermott';
const newName =
splitIntoFirstAndLastName(name);
console.log(name); // 'Ryan McDermott';
console.log(newName); // ['Ryan', 'McDermott'];
// Special care when working with arrays/obj
const addItemToCart = (cart, item) => {
return [...cart, { item, date: Date.now() }];
};
JS Clean Code:
Favor Functional
src: github.com/ryanmcdermott/clean-code-javascript
const programmers = [
{name: 'Uncle Bobby', linesOfCode: 500},
{name: 'Gracie Hopper', linesOfCode: 1000}];
// BAD
let totalOutput = 0;
for (let i = 0; i < programmerOutput.length;
i++) {
totalOutput += programmers[i].linesOfCode;
}
// GOOD
const totalOutput = programmers
.map((programmer) => programmer.linesOfCode)
.reduce((acc, linesOfCode) => acc +
linesOfCode, INITIAL_VALUE);
JS Clean Code:
Promises over CBs
src: github.com/ryanmcdermott/clean-code-javascript
// BAD
get(LINK, (requestErr, response) => {
if (requestErr) {...}
else {
writeFile('article.html', response.body, (writeErr) => {
if (writeErr) {...}
else {...}
});
}
});
// GOOD
get(LINK)
.then((response) => writeFile('article.html', response))
.then(() => {...})
.catch((err) => {...});
// BEST
async function getCleanCodeArticle() {
try {
const response = await get(LINK);
await writeFile('article.html', response);
} catch(err) {...}
}
"Code formatting is about communication,
and communication is the professional
developer’s first order of business."
Robert C. Martin, Clean Code: A Handbook of Agile Software Craftsmanship
Above all:
consistency
Thanks for your time!
Hope you enjoyed :)
Questions? bit.ly/arthurtdc
/aputhin

More Related Content

What's hot

PHP - Introduction to PHP Error Handling
PHP -  Introduction to PHP Error HandlingPHP -  Introduction to PHP Error Handling
PHP - Introduction to PHP Error Handling
Vibrant Technologies & Computers
 
Creating own language made easy
Creating own language made easyCreating own language made easy
Creating own language made easy
Ingvar Stepanyan
 
How To Think In Go
How To Think In GoHow To Think In Go
How To Think In Go
lestrrat
 
Errors, Exceptions & Logging (PHP Hants Oct '13)
Errors, Exceptions & Logging (PHP Hants Oct '13)Errors, Exceptions & Logging (PHP Hants Oct '13)
Errors, Exceptions & Logging (PHP Hants Oct '13)
James Titcumb
 
Getting Testy With Perl6
Getting Testy With Perl6Getting Testy With Perl6
Getting Testy With Perl6
Workhorse Computing
 
Beware: Sharp Tools
Beware: Sharp ToolsBeware: Sharp Tools
Beware: Sharp Toolschrismdp
 
Unit Testing Lots of Perl
Unit Testing Lots of PerlUnit Testing Lots of Perl
Unit Testing Lots of Perl
Workhorse Computing
 
Perl training-in-navi mumbai
Perl training-in-navi mumbaiPerl training-in-navi mumbai
Perl training-in-navi mumbai
vibrantuser
 
Zend Certification Preparation Tutorial
Zend Certification Preparation TutorialZend Certification Preparation Tutorial
Zend Certification Preparation Tutorial
Lorna Mitchell
 
Php Operators N Controllers
Php Operators N ControllersPhp Operators N Controllers
Php Operators N Controllersmussawir20
 
Getting testy with Perl
Getting testy with PerlGetting testy with Perl
Getting testy with Perl
Workhorse Computing
 
Static Analysis of PHP Code – IPC Berlin 2016
Static Analysis of PHP Code – IPC Berlin 2016Static Analysis of PHP Code – IPC Berlin 2016
Static Analysis of PHP Code – IPC Berlin 2016
Rouven Weßling
 
Effective Benchmarks
Effective BenchmarksEffective Benchmarks
Effective Benchmarks
Workhorse Computing
 
Functuon
FunctuonFunctuon
Functuon
NithyaNithyav
 
The promise of asynchronous PHP
The promise of asynchronous PHPThe promise of asynchronous PHP
The promise of asynchronous PHP
Wim Godden
 
Let's Talk Scope
Let's Talk ScopeLet's Talk Scope
Let's Talk Scope
Alena Holligan
 
Bioinformatics p4-io v2013-wim_vancriekinge
Bioinformatics p4-io v2013-wim_vancriekingeBioinformatics p4-io v2013-wim_vancriekinge
Bioinformatics p4-io v2013-wim_vancriekinge
Prof. Wim Van Criekinge
 
Php string function
Php string function Php string function
Php string function
Ravi Bhadauria
 
Php exceptions
Php exceptionsPhp exceptions
Php exceptions
Damian Sromek
 

What's hot (20)

PHP - Introduction to PHP Error Handling
PHP -  Introduction to PHP Error HandlingPHP -  Introduction to PHP Error Handling
PHP - Introduction to PHP Error Handling
 
Creating own language made easy
Creating own language made easyCreating own language made easy
Creating own language made easy
 
How To Think In Go
How To Think In GoHow To Think In Go
How To Think In Go
 
Errors, Exceptions & Logging (PHP Hants Oct '13)
Errors, Exceptions & Logging (PHP Hants Oct '13)Errors, Exceptions & Logging (PHP Hants Oct '13)
Errors, Exceptions & Logging (PHP Hants Oct '13)
 
Getting Testy With Perl6
Getting Testy With Perl6Getting Testy With Perl6
Getting Testy With Perl6
 
Beware: Sharp Tools
Beware: Sharp ToolsBeware: Sharp Tools
Beware: Sharp Tools
 
Unit Testing Lots of Perl
Unit Testing Lots of PerlUnit Testing Lots of Perl
Unit Testing Lots of Perl
 
Perl training-in-navi mumbai
Perl training-in-navi mumbaiPerl training-in-navi mumbai
Perl training-in-navi mumbai
 
Zend Certification Preparation Tutorial
Zend Certification Preparation TutorialZend Certification Preparation Tutorial
Zend Certification Preparation Tutorial
 
Php Operators N Controllers
Php Operators N ControllersPhp Operators N Controllers
Php Operators N Controllers
 
Getting testy with Perl
Getting testy with PerlGetting testy with Perl
Getting testy with Perl
 
Static Analysis of PHP Code – IPC Berlin 2016
Static Analysis of PHP Code – IPC Berlin 2016Static Analysis of PHP Code – IPC Berlin 2016
Static Analysis of PHP Code – IPC Berlin 2016
 
Effective Benchmarks
Effective BenchmarksEffective Benchmarks
Effective Benchmarks
 
Functuon
FunctuonFunctuon
Functuon
 
A Life of breakpoint
A Life of breakpointA Life of breakpoint
A Life of breakpoint
 
The promise of asynchronous PHP
The promise of asynchronous PHPThe promise of asynchronous PHP
The promise of asynchronous PHP
 
Let's Talk Scope
Let's Talk ScopeLet's Talk Scope
Let's Talk Scope
 
Bioinformatics p4-io v2013-wim_vancriekinge
Bioinformatics p4-io v2013-wim_vancriekingeBioinformatics p4-io v2013-wim_vancriekinge
Bioinformatics p4-io v2013-wim_vancriekinge
 
Php string function
Php string function Php string function
Php string function
 
Php exceptions
Php exceptionsPhp exceptions
Php exceptions
 

Similar to Clean & Typechecked JS

Static types on javascript?! Type checking approaches to ensure healthy appli...
Static types on javascript?! Type checking approaches to ensure healthy appli...Static types on javascript?! Type checking approaches to ensure healthy appli...
Static types on javascript?! Type checking approaches to ensure healthy appli...
Arthur Puthin
 
Game Design and Development Workshop Day 1
Game Design and Development Workshop Day 1Game Design and Development Workshop Day 1
Game Design and Development Workshop Day 1
Troy Miles
 
My programming final proj. (1)
My programming final proj. (1)My programming final proj. (1)
My programming final proj. (1)aeden_brines
 
Groovy Introduction - JAX Germany - 2008
Groovy Introduction - JAX Germany - 2008Groovy Introduction - JAX Germany - 2008
Groovy Introduction - JAX Germany - 2008
Guillaume Laforge
 
JavaScript and jQuery Fundamentals
JavaScript and jQuery FundamentalsJavaScript and jQuery Fundamentals
JavaScript and jQuery FundamentalsBG Java EE Course
 
Powerpoint presentation final requirement in fnd prg
Powerpoint presentation final requirement in fnd prgPowerpoint presentation final requirement in fnd prg
Powerpoint presentation final requirement in fnd prgalyssa-castro2326
 
Fundamentals of programming angeli
Fundamentals of programming angeliFundamentals of programming angeli
Fundamentals of programming angeli
bergonio11339481
 
Practical Ext JS Debugging
Practical Ext JS DebuggingPractical Ext JS Debugging
Practical Ext JS Debugging
Shea Frederick
 
Rust Workshop - NITC FOSSMEET 2017
Rust Workshop - NITC FOSSMEET 2017 Rust Workshop - NITC FOSSMEET 2017
Rust Workshop - NITC FOSSMEET 2017
pramode_ce
 
Haxe by sergei egorov
Haxe by sergei egorovHaxe by sergei egorov
Haxe by sergei egorov
Sergei Egorov
 
Java tut1
Java tut1Java tut1
Java tut1
Ajmal Khan
 
Tutorial java
Tutorial javaTutorial java
Tutorial java
Abdul Aziz
 
Java Tut1
Java Tut1Java Tut1
Java Tut1
guest5c8bd1
 

Similar to Clean & Typechecked JS (20)

Static types on javascript?! Type checking approaches to ensure healthy appli...
Static types on javascript?! Type checking approaches to ensure healthy appli...Static types on javascript?! Type checking approaches to ensure healthy appli...
Static types on javascript?! Type checking approaches to ensure healthy appli...
 
Game Design and Development Workshop Day 1
Game Design and Development Workshop Day 1Game Design and Development Workshop Day 1
Game Design and Development Workshop Day 1
 
My programming final proj. (1)
My programming final proj. (1)My programming final proj. (1)
My programming final proj. (1)
 
Groovy Introduction - JAX Germany - 2008
Groovy Introduction - JAX Germany - 2008Groovy Introduction - JAX Germany - 2008
Groovy Introduction - JAX Germany - 2008
 
JavaScript and jQuery Fundamentals
JavaScript and jQuery FundamentalsJavaScript and jQuery Fundamentals
JavaScript and jQuery Fundamentals
 
jQuery introduction
jQuery introductionjQuery introduction
jQuery introduction
 
C Tutorials
C TutorialsC Tutorials
C Tutorials
 
Powerpoint presentation final requirement in fnd prg
Powerpoint presentation final requirement in fnd prgPowerpoint presentation final requirement in fnd prg
Powerpoint presentation final requirement in fnd prg
 
Fundamentals of programming angeli
Fundamentals of programming angeliFundamentals of programming angeli
Fundamentals of programming angeli
 
C tutorial
C tutorialC tutorial
C tutorial
 
C tutorial
C tutorialC tutorial
C tutorial
 
C tutorial
C tutorialC tutorial
C tutorial
 
Practical Ext JS Debugging
Practical Ext JS DebuggingPractical Ext JS Debugging
Practical Ext JS Debugging
 
CGI.ppt
CGI.pptCGI.ppt
CGI.ppt
 
Rust Workshop - NITC FOSSMEET 2017
Rust Workshop - NITC FOSSMEET 2017 Rust Workshop - NITC FOSSMEET 2017
Rust Workshop - NITC FOSSMEET 2017
 
Haxe by sergei egorov
Haxe by sergei egorovHaxe by sergei egorov
Haxe by sergei egorov
 
Java tut1
Java tut1Java tut1
Java tut1
 
Java Tutorial
Java TutorialJava Tutorial
Java Tutorial
 
Tutorial java
Tutorial javaTutorial java
Tutorial java
 
Java Tut1
Java Tut1Java Tut1
Java Tut1
 

Recently uploaded

GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
Neo4j
 
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
James Anderson
 
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdfUni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems S.M.S.A.
 
GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...
ThomasParaiso2
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
Quotidiano Piemontese
 
20240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 202420240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 2024
Matthew Sinclair
 
Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
Alpen-Adria-Universität
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
Ralf Eggert
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
James Anderson
 
20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
Matthew Sinclair
 
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Nexer Digital
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
Jemma Hussein Allen
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
KatiaHIMEUR1
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance
 
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
Neo4j
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
 
Microsoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdfMicrosoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdf
Uni Systems S.M.S.A.
 
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdfSAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
Peter Spielvogel
 
Pushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 daysPushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 days
Adtran
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
Alan Dix
 

Recently uploaded (20)

GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
 
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
 
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdfUni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdf
 
GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
 
20240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 202420240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 2024
 
Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
 
20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
 
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
 
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
 
Microsoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdfMicrosoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdf
 
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdfSAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
 
Pushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 daysPushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 days
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
 

Clean & Typechecked JS

  • 1. Clean and Typechecked JS Arthur Reis Puthin
  • 2. About me Developer at ilegra (think beyond!) Mostly front-end stuff Undergraduate at Unisinos /aputhin
  • 3. Para enviar uma pergunta e receber o material desta apresentação acesse: bit.ly/arthurtdc
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 10. Let's fix it where we are best at: the code
  • 11. "The most often-cited rationales for type systems are that they: 1. Catch errors early 2. Improve readability of code 3. Facilitate tooling 4. Improve runtime performance" http://www.hammerlab.org/2015/12/09/our-experiences-with-flow/
  • 12. "The results are encouraging; we found that using Flow or TypeScript could have prevented 15% of the public bugs for public projects on GitHub." http://ttendency.cs.ucl.ac.uk/projects/type_study/
  • 13.
  • 14. Pick your poison: ➔ Supersets (i.e. TypeScript or JavaScript++) ➔ Static Typecheckers (i.e. Flow) ➔ Compile to JS (i.e. Elm or PureScript)
  • 16. How does it work? // @flow function sqr(n: number): number { return n * n; } sqr("2"); // Error! // setup babel to clean it up // install the binary npm install --save-dev flow-bin // add it to package.json "scripts": {"flow": "flow"} // run to check for errors npm run flow init npm run flow npm run flow stop
  • 17. Type Annotation Basics let isOpen: boolean = true; const answer: number = 42; // includes Infinity and NaN let company: string = 'ilegra'; const hope: null = null; let theQuestion: void = undefined; // uncompatible with null! const words: Array<string> = ['I', 'am', 'groot']; // Array<T> let iCanBeAnything: any = 'es' + 2016; // wildcard, DON'T USE IT // "Using any is completely unsafe, and should be avoided whenever possible" - https://flow.org/en/docs/types/any/
  • 18. Object & Function Typing let proplessObject: Object = {}; // works, but loses typechecking goodness const identity: { name: string, age: number } = { name: 'Arthur', age: 26, }; let booksPageCounts: { [name: string]: number } = { Javascript: 999, JSGoodParts: 100, }; const calculateArea = (radius: number): number => { // return type is optional return 3.14 * radius * radius; };
  • 19. Type Alias type Address = { street: string, number: number }; let myWorkAdress: Address = { street: 'Washington Luiz', number: 820, }; type Email = string; // aliasing var myEmail: Email = 'arthur.rprp@gmail.com';
  • 20. Generics, Maybe and Optionals type Password<T> = { key: T }; let numberKey: Password<number> = { key: 12345678 }; let stringKey: Password<string> = { key: "shhhhh" }; let arrayKey: Password<Array<number>> = { key: [4, 2] } var message: ?string = null; // accepts string, null or undefined function acceptsOptString(value?: string) {} // accepts string or undefined
  • 21. Literals & Union function getColor(name: "success" | "warning" | "danger") { // ... } getColor("success"); // Works! getColor("danger"); // Works! getColor("error"); // Error! // accepts any number, boolean or string function toStringPrimitives(value: number | boolean | string) { return String(value); }
  • 23. Types: ✓ But we have to go further...
  • 24. “It is not the language that makes programs appear simple. It is the programmer that make the language appear simple!” Robert C. Martin, Clean Code: A Handbook of Agile Software Craftsmanship
  • 25. Keep an eye for code smells...
  • 26. Code Smells: Non-strict Equality // All of these evaluate to 'true' console.log(false == '0'); console.log(null == undefined); console.log(" trn" == 0); console.log('' == 0); console.log(0 == '0'); if ({}) {...} if ([]) {...} // Always go for strict equality/inequality console.log(0 === '0'); // false // random gotcha: NaN comparison console.log(NaN == NaN); // false console.log(NaN === NaN); // false console.log(isNaN(NaN)); // true, but beware console.log(NaN != NaN); // true
  • 27. Code Smells: Incorrect context Game.prototype.restart = function () { this.clearLocalStorage(); this.timer = setTimeout(function() { this.clearBoard(); // what is "this"? }, 0); }; // Solution 1: explicit binding with .bind() let clearInTime = function() { this.clearBoard(); }; this.clearInTime = clearInTime.bind(this); // Solution 2: arrow functions this.clearInTime = setTimeout(() => { this.clearBoard(); }, 0);
  • 28. Code Smells: Variable scoping and handling for (var i = 0; i < 10; i++) { elements[i].onclick = function() { console.log("This is element #" + i); // 10 }; } console.log(i); // = 10; i "leaks" out of scope // solution: let (ES6) is block-level scoped function () { var a = 1; let b = 2; } console.log(a); // 1 console.log(b); // undefined /* const is NOT for scope hoisting: it is for read-only/immutable values! */
  • 29. Code Smells: Anonymous Functions // debugging this stack trace might go awry... document.querySelector('button') .addEventListener('input', function(e) { // ... }); // naming favors stack-tracing and code reuse const kaboom = function() { alert('Ka-boom') }; document.querySelector('button') .addEventListener('click', kaboom); document.querySelector('#egg') .addEventListener('mouseenter', kaboom);
  • 30. More Anti-patterns to keep in mind... - Too many global namespace variables - Too much direct DOM manipulation - Modifying the Object class prototype (or any prototype for that matter…)
  • 31. JS Clean Code: Fewer Arguments // BAD function createMenu(title, body, buttonText, cancellable) {...} // GOOD function createMenu({ title, body, buttonText, cancellable }) {...} createMenu({ title: 'Foo', body: 'Bar', buttonText: 'Baz', cancellable: true }); src: github.com/ryanmcdermott/clean-code-javascript
  • 32. JS Clean Code: Avoid Side Effects src: github.com/ryanmcdermott/clean-code-javascript function splitIntoFirstAndLastName(name) { return name.split(' '); } const name = 'Ryan McDermott'; const newName = splitIntoFirstAndLastName(name); console.log(name); // 'Ryan McDermott'; console.log(newName); // ['Ryan', 'McDermott']; // Special care when working with arrays/obj const addItemToCart = (cart, item) => { return [...cart, { item, date: Date.now() }]; };
  • 33. JS Clean Code: Favor Functional src: github.com/ryanmcdermott/clean-code-javascript const programmers = [ {name: 'Uncle Bobby', linesOfCode: 500}, {name: 'Gracie Hopper', linesOfCode: 1000}]; // BAD let totalOutput = 0; for (let i = 0; i < programmerOutput.length; i++) { totalOutput += programmers[i].linesOfCode; } // GOOD const totalOutput = programmers .map((programmer) => programmer.linesOfCode) .reduce((acc, linesOfCode) => acc + linesOfCode, INITIAL_VALUE);
  • 34. JS Clean Code: Promises over CBs src: github.com/ryanmcdermott/clean-code-javascript // BAD get(LINK, (requestErr, response) => { if (requestErr) {...} else { writeFile('article.html', response.body, (writeErr) => { if (writeErr) {...} else {...} }); } }); // GOOD get(LINK) .then((response) => writeFile('article.html', response)) .then(() => {...}) .catch((err) => {...}); // BEST async function getCleanCodeArticle() { try { const response = await get(LINK); await writeFile('article.html', response); } catch(err) {...} }
  • 35. "Code formatting is about communication, and communication is the professional developer’s first order of business." Robert C. Martin, Clean Code: A Handbook of Agile Software Craftsmanship
  • 37.
  • 38. Thanks for your time! Hope you enjoyed :) Questions? bit.ly/arthurtdc /aputhin