SlideShare a Scribd company logo
1 of 58
Download to read offline
Flow for JavaScript
Imposing structure on a freeform world
Ikai Lan
@ikai
About me
• Ikai Lan, new to Medium, new to JavaScript
• … hopefully not new to programming
• Based out of San Francisco, but I love New York
City
•
Favorite emoji: 😐
Here tonight
Platform engineering
Why type checking?
“I want to build a
house … ”
“… so I got some raw materials,
and I built one.”
More people want to
move in …
Now you need some
rules, before things get
out of hand…
The array that wasn’t.
// Before the fix



getLatestPosts(userId) {

if (!userId) {

return Q.resolve(null)

}



// More code here to fetch posts and 

// return a Promise

}
The array that wasn’t.
// Somewhere several layers up 

// the stack

let result = client.getLatestPosts(currentUserId)

result.forEach((value) => { ... }) 

The array that wasn’t.
// Somewhere several layers up 

// the stack

let result = client.getLatestPosts(currentUserId)

result.forEach((value) => { ... }) 

Uncaught TypeError: Cannot read property 'foreach' of
null(…)
The array that wasn’t.




getLatestPosts(userId) {

if (!userId) {

return Q.resolve([])

}



// More code here to fetch posts and 

// return a Promise

}
The array that wasn’t.




getLatestPosts(userId) {

if (!userId) {

return Q.resolve([])

}



// More code here to fetch posts and 

// return a Promise

}
[]
Yet, the docs …
/**

* @return {Promise<Array<Post>>} A sample of 

* the user's posts 

*/

getLatestPosts(userId) {

if (!userId) {

return Q.resolve(null)

}

// More code here to fetch posts and

// return a Promise

}
Yet, the docs …
/**

* @return {Promise<Array<Post>>} A sample of 

* the user's posts 

*/

getLatestPosts(userId) {

if (!userId) {

return Q.resolve(null)

}

// More code here to fetch posts and

// return a Promise

}
/**

* @return {Promise<Array<Post>>} A sample of 

* the user's posts 

*/
Without automatic checks,
there is decay …
I want an object!
- var recommendedPostRelationsPromise =
this._postUserService.getVotesForUserId(followedUserId,
recommendedSince)

+ var recommendedPostRelationsPromise =
this._postUserService.getVotesForUserId(followedUserId,
{votedAfter: recommendedSince})
I want an object!
- var recommendedPostRelationsPromise =
this._postUserService.getVotesForUserId(followedUserId,
recommendedSince)

+ var recommendedPostRelationsPromise =
this._postUserService.getVotesForUserId(followedUserId,
{votedAfter: recommendedSince})
What if that value is
undefined?
/**

* @returns an Array of only recent votes

*/

getVotesForUserId(userId, filterParams) {

// Limit results returned to items greater
// than this parameter

return queryForVotesAfter(
filterParams.recommendedSince)

}

This isn’t horror story
hour
Closure Flow
Google Facebook
Type annotations in docs Type annotations inline
Valid JavaScript Requires transformation
Convert entire codebase File-by-file
Closure Flow
Google Facebook
Type annotations in docs Type annotations inline
Valid JavaScript Requires transformation
Convert entire codebase File-by-file
How do we add types?
‘use strict’ // @flow
First line of a file to annotate
Flow annotated JavaScript
buildQuery(path, options) {
buildQuery(path: string,
options: GoSocialRequestOptions): string {
Flow annotated JavaScript
buildQuery(path, options) {
buildQuery(path: string,
options: GoSocialRequestOptions): string {
Parameter types
Flow annotated JavaScript
buildQuery(path, options) {
buildQuery(path: string,
options: GoSocialRequestOptions): string {
Return type
Lint
Flow
Test
Lint
Flow
Test
Which methods in files with @flow
are missing annotations?
Lint
Flow
Test
Do the types match up? Do they
make sense?
server/graph/common/goSocialClient.js:382
382: .then((result: any): Array<T> => {
^^^^^^^^ array type. This type is incompatible with
12: onFulfill?: (value: R) => KewPromise<U> | U,
^^^^^^^^^^^^^^^^^ union: type application of identifier
`KewPromise` | type parameter `U` of call of method `then`. See lib: style-guide/flow-interfaces.js:
12
Member 1:
12: onFulfill?: (value: R) => KewPromise<U> | U,
^^^^^^^^^^^^^ type application of identifier `KewPromise`. See
lib: style-guide/flow-interfaces.js:12
Error:
382: .then((result: any): Array<T> => {
^^^^^^^^ array type. This type is incompatible with
12: onFulfill?: (value: R) => KewPromise<U> | U,
^^^^^^^^^^^^^ KewPromise. See lib: style-guide/flow-
interfaces.js:12
Member 2:
381: return this.request(requestData)
^ type parameter `U` of call of method `then`
Error:
382: .then((result: any): Array<T> => {
^^^^^^^^ array type. This type is incompatible with
373: fetchObjects<T: RpcSchema>(Ctor: Class<T>, options: GoSocialRequestOptions): Promise<T> {
^ some incompatible instantiation of `T`
When flow complains …
Lint
Flow
Test
Do the unit and functional tests
still pass? Manual poking
type GoSocialRequestOptions = {

method?: string,

requestType?: string,

type?: string,

path?: string,

udpEvent?: Object,

shape?: string,

query?: Object,

properties?: Object,

}
{} as a parameter
What makes this project challenging?
We needed to figure out
the dependency graph.
LoginService
AuthManager
UserManager
Depends on …
Depends on …
Why the dependency graph
matters
Our graph 😭 😭 😭
The method docs are out of date.
Remember this?
/**

* @return {Promise<Array<Post>>} A sample of 

* the user's posts 

*/

getLatestPosts(userId) {

if (!userId) {

return Q.resolve(null)

}

// More code here to fetch posts and

// return a Promise

}
We have to define interfaces for
third party libraries
// Source: https://github.com/moment/moment/blob/develop/moment.d.ts

declare class Moment {

subtract(val: number, unit: string): this;

add(amount: number, unitOfTime: string): this;

diff(b: Moment, unitOfTime?: string, round?: boolean): number;

startOf(unit: string): this;

valueOf(): number;

}



declare module 'moment' {

declare function utc(): Moment;

declare function exports(): Moment;

}
Mistakes are buried
layers deep - changes need to
be made that don’t result in
unintended consequences
OCaml 😐
One more thing: nulls.
create(tag: Tag): Promise<?Tag>
This value is NOT allowed to be null
create(tag: Tag): Promise<?Tag>
This value is allowed to be null!
create(tag: Tag): Promise<Tag> {

let tag = null;



if (someCondition) {

tag = new Tag()

}



return Q.resolve(tag)

}

No ‘?’ to show that return type is nullable
ERROR
create(tag: Tag): Promise<?Tag> {

let tag = null;



if (someCondition) {

tag = new Tag()

}



return Q.resolve(tag)

}

‘?’ shows that return type is nullable
Correct!
Now everything this touches
• Has to null check (via a conditional) - subtle
changes in how code works
• Or accept a type ?Tag, which means “nullable
type”
• Adding to existing code can be tricky without
introducing subtle changes
But this is also good
• Makes us really think about which methods will
always have a valid object, which will not
• Will lead to better API design long term
But it can be confusing
function myNullableString(input: ?string): number {

return input.length;

}



function callerOfMyNullableString(input: string): number {

return myNullableString(input);

}

function myNullableString(input: ?string): number {

return input.length;

}



function callerOfMyNullableString(input: string): number {

return myNullableString(input);

}

input: ?string
input: string
This is valid
This is not valid
function myArray(input: Array<?string>): number {

return input.length;

}









function callerOfMyArray(input: Array<string>): number
{

return myArrayWithNullableObjects(input);

}
Here’s why
function myArray(input: Array<?string>): number
{

input.append(null);

return input.length;

}
function callerOfMyArray(input: Array<string>): number {

return myArrayWithNullableObjects(input);

}
No longer valid!
Organizational challenges
• General organization buy-in
• Flow is almost an entirely new language that
people need to learn
• Working against a moving target
• Funny things that happen after merges
To recap
• We are finding it hard to scale development
without types
• Adding types to untyped code has a number of
challenges, technical and otherwise
• We believe the payoff will be totally worth it.
Thank you!
• Thanks to Kelly, Nick, Gianni for being great
teammates and teaching me everything
• Thanks to Madeline for organizing this great
event!
• Image source: unsplash.com
Q&A
• If you come up with someone, just ask one of us!
• Twitter/Medium: @ikai

More Related Content

What's hot

Design patterns in java script, jquery, angularjs
Design patterns in java script, jquery, angularjsDesign patterns in java script, jquery, angularjs
Design patterns in java script, jquery, angularjsRavi Bhadauria
 
Swift in SwiftUI
Swift in SwiftUISwift in SwiftUI
Swift in SwiftUIBongwon Lee
 
Javaslang Talk @ Javaland 2017
Javaslang Talk @ Javaland 2017Javaslang Talk @ Javaland 2017
Javaslang Talk @ Javaland 2017David Schmitz
 
JavaScript For CSharp Developer
JavaScript For CSharp DeveloperJavaScript For CSharp Developer
JavaScript For CSharp DeveloperSarvesh Kushwaha
 
What You Need to Know about Lambdas
What You Need to Know about LambdasWhat You Need to Know about Lambdas
What You Need to Know about LambdasRyan Knight
 
Angular Weekend
Angular WeekendAngular Weekend
Angular WeekendTroy Miles
 
Functional Principles for OO Developers
Functional Principles for OO DevelopersFunctional Principles for OO Developers
Functional Principles for OO Developersjessitron
 
TDD and mobile development: some forgotten techniques, illustrated with Android
TDD and mobile development: some forgotten techniques, illustrated with AndroidTDD and mobile development: some forgotten techniques, illustrated with Android
TDD and mobile development: some forgotten techniques, illustrated with AndroidCodemotion
 
JavaScript Objects
JavaScript ObjectsJavaScript Objects
JavaScript ObjectsReem Alattas
 
Akka Futures and Akka Remoting
Akka Futures  and Akka RemotingAkka Futures  and Akka Remoting
Akka Futures and Akka RemotingKnoldus Inc.
 
React Native One Day
React Native One DayReact Native One Day
React Native One DayTroy Miles
 
Architecture for scalable Angular applications
Architecture for scalable Angular applicationsArchitecture for scalable Angular applications
Architecture for scalable Angular applicationsPaweł Żurowski
 
Javascript basics
Javascript basicsJavascript basics
Javascript basicsSolv AS
 
Swift, functional programming, and the future of Objective-C
Swift, functional programming, and the future of Objective-CSwift, functional programming, and the future of Objective-C
Swift, functional programming, and the future of Objective-CAlexis Gallagher
 
Contracts in-clojure-pete
Contracts in-clojure-peteContracts in-clojure-pete
Contracts in-clojure-petejessitron
 

What's hot (20)

Quick swift tour
Quick swift tourQuick swift tour
Quick swift tour
 
Design patterns in java script, jquery, angularjs
Design patterns in java script, jquery, angularjsDesign patterns in java script, jquery, angularjs
Design patterns in java script, jquery, angularjs
 
Swift in SwiftUI
Swift in SwiftUISwift in SwiftUI
Swift in SwiftUI
 
Javaslang Talk @ Javaland 2017
Javaslang Talk @ Javaland 2017Javaslang Talk @ Javaland 2017
Javaslang Talk @ Javaland 2017
 
JavaScript For CSharp Developer
JavaScript For CSharp DeveloperJavaScript For CSharp Developer
JavaScript For CSharp Developer
 
Javaslang @ Devoxx
Javaslang @ DevoxxJavaslang @ Devoxx
Javaslang @ Devoxx
 
What You Need to Know about Lambdas
What You Need to Know about LambdasWhat You Need to Know about Lambdas
What You Need to Know about Lambdas
 
Angular Weekend
Angular WeekendAngular Weekend
Angular Weekend
 
Functional Principles for OO Developers
Functional Principles for OO DevelopersFunctional Principles for OO Developers
Functional Principles for OO Developers
 
TDD and mobile development: some forgotten techniques, illustrated with Android
TDD and mobile development: some forgotten techniques, illustrated with AndroidTDD and mobile development: some forgotten techniques, illustrated with Android
TDD and mobile development: some forgotten techniques, illustrated with Android
 
JavaScript Objects
JavaScript ObjectsJavaScript Objects
JavaScript Objects
 
Akka Futures and Akka Remoting
Akka Futures  and Akka RemotingAkka Futures  and Akka Remoting
Akka Futures and Akka Remoting
 
React Native One Day
React Native One DayReact Native One Day
React Native One Day
 
Javascript Design Patterns
Javascript Design PatternsJavascript Design Patterns
Javascript Design Patterns
 
Writing testable code
Writing testable codeWriting testable code
Writing testable code
 
Architecture for scalable Angular applications
Architecture for scalable Angular applicationsArchitecture for scalable Angular applications
Architecture for scalable Angular applications
 
Javascript basics
Javascript basicsJavascript basics
Javascript basics
 
Workflow Foundation 4
Workflow Foundation 4Workflow Foundation 4
Workflow Foundation 4
 
Swift, functional programming, and the future of Objective-C
Swift, functional programming, and the future of Objective-CSwift, functional programming, and the future of Objective-C
Swift, functional programming, and the future of Objective-C
 
Contracts in-clojure-pete
Contracts in-clojure-peteContracts in-clojure-pete
Contracts in-clojure-pete
 

Similar to Structure on a freeform world

Working effectively with legacy code
Working effectively with legacy codeWorking effectively with legacy code
Working effectively with legacy codeShriKant Vashishtha
 
Extreme Swift
Extreme SwiftExtreme Swift
Extreme SwiftMovel
 
Clean Code: Chapter 3 Function
Clean Code: Chapter 3 FunctionClean Code: Chapter 3 Function
Clean Code: Chapter 3 FunctionKent Huang
 
Functional Vaadin talk at OSCON 2014
Functional Vaadin talk at OSCON 2014Functional Vaadin talk at OSCON 2014
Functional Vaadin talk at OSCON 2014hezamu
 
Protocol-Oriented Networking
Protocol-Oriented NetworkingProtocol-Oriented Networking
Protocol-Oriented NetworkingMostafa Amer
 
Ajax Under The Hood
Ajax Under The HoodAjax Under The Hood
Ajax Under The HoodWO Community
 
"Scala in Goozy", Alexey Zlobin
"Scala in Goozy", Alexey Zlobin "Scala in Goozy", Alexey Zlobin
"Scala in Goozy", Alexey Zlobin Vasil Remeniuk
 
Rethinking Syncing at AltConf 2019
Rethinking Syncing at AltConf 2019Rethinking Syncing at AltConf 2019
Rethinking Syncing at AltConf 2019Joe Keeley
 
Alternatives of JPA/Hibernate
Alternatives of JPA/HibernateAlternatives of JPA/Hibernate
Alternatives of JPA/HibernateSunghyouk Bae
 
TypeScript Presentation - Jason Haffey
TypeScript Presentation - Jason HaffeyTypeScript Presentation - Jason Haffey
TypeScript Presentation - Jason HaffeyRalph Johnson
 
API first with Swagger and Scala by Slava Schmidt
API first with Swagger and Scala by  Slava SchmidtAPI first with Swagger and Scala by  Slava Schmidt
API first with Swagger and Scala by Slava SchmidtJavaDayUA
 
Extensible Operators and Literals for JavaScript
Extensible Operators and Literals for JavaScriptExtensible Operators and Literals for JavaScript
Extensible Operators and Literals for JavaScriptBrendan Eich
 
Intro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran MizrahiIntro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran MizrahiRan Mizrahi
 
Building Single-Page Web Appplications in dart - Devoxx France 2013
Building Single-Page Web Appplications in dart - Devoxx France 2013Building Single-Page Web Appplications in dart - Devoxx France 2013
Building Single-Page Web Appplications in dart - Devoxx France 2013yohanbeschi
 
ASP.Net 5 and C# 6
ASP.Net 5 and C# 6ASP.Net 5 and C# 6
ASP.Net 5 and C# 6Andy Butland
 
RIAs Done Right: Grails, Flex, and EXT GWT
RIAs Done Right: Grails, Flex, and EXT GWTRIAs Done Right: Grails, Flex, and EXT GWT
RIAs Done Right: Grails, Flex, and EXT GWTMichael Galpin
 
Применение паттерна Page Object для автоматизации веб сервисов
Применение паттерна Page Object для автоматизации веб сервисовПрименение паттерна Page Object для автоматизации веб сервисов
Применение паттерна Page Object для автоматизации веб сервисовCOMAQA.BY
 
An introduction to functional programming with Swift
An introduction to functional programming with SwiftAn introduction to functional programming with Swift
An introduction to functional programming with SwiftFatih Nayebi, Ph.D.
 

Similar to Structure on a freeform world (20)

Working effectively with legacy code
Working effectively with legacy codeWorking effectively with legacy code
Working effectively with legacy code
 
Extreme Swift
Extreme SwiftExtreme Swift
Extreme Swift
 
Clean Code: Chapter 3 Function
Clean Code: Chapter 3 FunctionClean Code: Chapter 3 Function
Clean Code: Chapter 3 Function
 
Functional Vaadin talk at OSCON 2014
Functional Vaadin talk at OSCON 2014Functional Vaadin talk at OSCON 2014
Functional Vaadin talk at OSCON 2014
 
Protocol-Oriented Networking
Protocol-Oriented NetworkingProtocol-Oriented Networking
Protocol-Oriented Networking
 
Naver_alternative_to_jpa
Naver_alternative_to_jpaNaver_alternative_to_jpa
Naver_alternative_to_jpa
 
Ajax Under The Hood
Ajax Under The HoodAjax Under The Hood
Ajax Under The Hood
 
"Scala in Goozy", Alexey Zlobin
"Scala in Goozy", Alexey Zlobin "Scala in Goozy", Alexey Zlobin
"Scala in Goozy", Alexey Zlobin
 
Rethinking Syncing at AltConf 2019
Rethinking Syncing at AltConf 2019Rethinking Syncing at AltConf 2019
Rethinking Syncing at AltConf 2019
 
Alternatives of JPA/Hibernate
Alternatives of JPA/HibernateAlternatives of JPA/Hibernate
Alternatives of JPA/Hibernate
 
TypeScript Presentation - Jason Haffey
TypeScript Presentation - Jason HaffeyTypeScript Presentation - Jason Haffey
TypeScript Presentation - Jason Haffey
 
API first with Swagger and Scala by Slava Schmidt
API first with Swagger and Scala by  Slava SchmidtAPI first with Swagger and Scala by  Slava Schmidt
API first with Swagger and Scala by Slava Schmidt
 
Extensible Operators and Literals for JavaScript
Extensible Operators and Literals for JavaScriptExtensible Operators and Literals for JavaScript
Extensible Operators and Literals for JavaScript
 
Intro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran MizrahiIntro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran Mizrahi
 
Building Single-Page Web Appplications in dart - Devoxx France 2013
Building Single-Page Web Appplications in dart - Devoxx France 2013Building Single-Page Web Appplications in dart - Devoxx France 2013
Building Single-Page Web Appplications in dart - Devoxx France 2013
 
ASP.Net 5 and C# 6
ASP.Net 5 and C# 6ASP.Net 5 and C# 6
ASP.Net 5 and C# 6
 
Angular2 for Beginners
Angular2 for BeginnersAngular2 for Beginners
Angular2 for Beginners
 
RIAs Done Right: Grails, Flex, and EXT GWT
RIAs Done Right: Grails, Flex, and EXT GWTRIAs Done Right: Grails, Flex, and EXT GWT
RIAs Done Right: Grails, Flex, and EXT GWT
 
Применение паттерна Page Object для автоматизации веб сервисов
Применение паттерна Page Object для автоматизации веб сервисовПрименение паттерна Page Object для автоматизации веб сервисов
Применение паттерна Page Object для автоматизации веб сервисов
 
An introduction to functional programming with Swift
An introduction to functional programming with SwiftAn introduction to functional programming with Swift
An introduction to functional programming with Swift
 

Recently uploaded

Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️anilsa9823
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
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
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
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.
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AIABDERRAOUF MEHENNI
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 

Recently uploaded (20)

Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
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
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
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...
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 

Structure on a freeform world

  • 1. Flow for JavaScript Imposing structure on a freeform world Ikai Lan @ikai
  • 2. About me • Ikai Lan, new to Medium, new to JavaScript • … hopefully not new to programming • Based out of San Francisco, but I love New York City • Favorite emoji: 😐
  • 6. “I want to build a house … ”
  • 7. “… so I got some raw materials, and I built one.”
  • 8. More people want to move in …
  • 9. Now you need some rules, before things get out of hand…
  • 10. The array that wasn’t. // Before the fix
 
 getLatestPosts(userId) {
 if (!userId) {
 return Q.resolve(null)
 }
 
 // More code here to fetch posts and 
 // return a Promise
 }
  • 11. The array that wasn’t. // Somewhere several layers up 
 // the stack
 let result = client.getLatestPosts(currentUserId)
 result.forEach((value) => { ... }) 

  • 12. The array that wasn’t. // Somewhere several layers up 
 // the stack
 let result = client.getLatestPosts(currentUserId)
 result.forEach((value) => { ... }) 
 Uncaught TypeError: Cannot read property 'foreach' of null(…)
  • 13. The array that wasn’t. 
 
 getLatestPosts(userId) {
 if (!userId) {
 return Q.resolve([])
 }
 
 // More code here to fetch posts and 
 // return a Promise
 }
  • 14. The array that wasn’t. 
 
 getLatestPosts(userId) {
 if (!userId) {
 return Q.resolve([])
 }
 
 // More code here to fetch posts and 
 // return a Promise
 } []
  • 15. Yet, the docs … /**
 * @return {Promise<Array<Post>>} A sample of 
 * the user's posts 
 */
 getLatestPosts(userId) {
 if (!userId) {
 return Q.resolve(null)
 }
 // More code here to fetch posts and
 // return a Promise
 }
  • 16. Yet, the docs … /**
 * @return {Promise<Array<Post>>} A sample of 
 * the user's posts 
 */
 getLatestPosts(userId) {
 if (!userId) {
 return Q.resolve(null)
 }
 // More code here to fetch posts and
 // return a Promise
 } /**
 * @return {Promise<Array<Post>>} A sample of 
 * the user's posts 
 */
  • 18. I want an object! - var recommendedPostRelationsPromise = this._postUserService.getVotesForUserId(followedUserId, recommendedSince)
 + var recommendedPostRelationsPromise = this._postUserService.getVotesForUserId(followedUserId, {votedAfter: recommendedSince})
  • 19. I want an object! - var recommendedPostRelationsPromise = this._postUserService.getVotesForUserId(followedUserId, recommendedSince)
 + var recommendedPostRelationsPromise = this._postUserService.getVotesForUserId(followedUserId, {votedAfter: recommendedSince})
  • 20. What if that value is undefined? /**
 * @returns an Array of only recent votes
 */
 getVotesForUserId(userId, filterParams) {
 // Limit results returned to items greater // than this parameter
 return queryForVotesAfter( filterParams.recommendedSince)
 }

  • 21. This isn’t horror story hour
  • 22. Closure Flow Google Facebook Type annotations in docs Type annotations inline Valid JavaScript Requires transformation Convert entire codebase File-by-file
  • 23. Closure Flow Google Facebook Type annotations in docs Type annotations inline Valid JavaScript Requires transformation Convert entire codebase File-by-file
  • 24. How do we add types? ‘use strict’ // @flow First line of a file to annotate
  • 25. Flow annotated JavaScript buildQuery(path, options) { buildQuery(path: string, options: GoSocialRequestOptions): string {
  • 26. Flow annotated JavaScript buildQuery(path, options) { buildQuery(path: string, options: GoSocialRequestOptions): string { Parameter types
  • 27. Flow annotated JavaScript buildQuery(path, options) { buildQuery(path: string, options: GoSocialRequestOptions): string { Return type
  • 29. Lint Flow Test Which methods in files with @flow are missing annotations?
  • 30. Lint Flow Test Do the types match up? Do they make sense?
  • 31. server/graph/common/goSocialClient.js:382 382: .then((result: any): Array<T> => { ^^^^^^^^ array type. This type is incompatible with 12: onFulfill?: (value: R) => KewPromise<U> | U, ^^^^^^^^^^^^^^^^^ union: type application of identifier `KewPromise` | type parameter `U` of call of method `then`. See lib: style-guide/flow-interfaces.js: 12 Member 1: 12: onFulfill?: (value: R) => KewPromise<U> | U, ^^^^^^^^^^^^^ type application of identifier `KewPromise`. See lib: style-guide/flow-interfaces.js:12 Error: 382: .then((result: any): Array<T> => { ^^^^^^^^ array type. This type is incompatible with 12: onFulfill?: (value: R) => KewPromise<U> | U, ^^^^^^^^^^^^^ KewPromise. See lib: style-guide/flow- interfaces.js:12 Member 2: 381: return this.request(requestData) ^ type parameter `U` of call of method `then` Error: 382: .then((result: any): Array<T> => { ^^^^^^^^ array type. This type is incompatible with 373: fetchObjects<T: RpcSchema>(Ctor: Class<T>, options: GoSocialRequestOptions): Promise<T> { ^ some incompatible instantiation of `T` When flow complains …
  • 32. Lint Flow Test Do the unit and functional tests still pass? Manual poking
  • 33. type GoSocialRequestOptions = {
 method?: string,
 requestType?: string,
 type?: string,
 path?: string,
 udpEvent?: Object,
 shape?: string,
 query?: Object,
 properties?: Object,
 } {} as a parameter
  • 34. What makes this project challenging?
  • 35. We needed to figure out the dependency graph.
  • 36. LoginService AuthManager UserManager Depends on … Depends on … Why the dependency graph matters
  • 37. Our graph 😭 😭 😭
  • 38. The method docs are out of date.
  • 39. Remember this? /**
 * @return {Promise<Array<Post>>} A sample of 
 * the user's posts 
 */
 getLatestPosts(userId) {
 if (!userId) {
 return Q.resolve(null)
 }
 // More code here to fetch posts and
 // return a Promise
 }
  • 40. We have to define interfaces for third party libraries
  • 41. // Source: https://github.com/moment/moment/blob/develop/moment.d.ts
 declare class Moment {
 subtract(val: number, unit: string): this;
 add(amount: number, unitOfTime: string): this;
 diff(b: Moment, unitOfTime?: string, round?: boolean): number;
 startOf(unit: string): this;
 valueOf(): number;
 }
 
 declare module 'moment' {
 declare function utc(): Moment;
 declare function exports(): Moment;
 }
  • 42. Mistakes are buried layers deep - changes need to be made that don’t result in unintended consequences
  • 44. One more thing: nulls.
  • 45. create(tag: Tag): Promise<?Tag> This value is NOT allowed to be null
  • 46. create(tag: Tag): Promise<?Tag> This value is allowed to be null!
  • 47. create(tag: Tag): Promise<Tag> {
 let tag = null;
 
 if (someCondition) {
 tag = new Tag()
 }
 
 return Q.resolve(tag)
 }
 No ‘?’ to show that return type is nullable ERROR
  • 48. create(tag: Tag): Promise<?Tag> {
 let tag = null;
 
 if (someCondition) {
 tag = new Tag()
 }
 
 return Q.resolve(tag)
 }
 ‘?’ shows that return type is nullable Correct!
  • 49. Now everything this touches • Has to null check (via a conditional) - subtle changes in how code works • Or accept a type ?Tag, which means “nullable type” • Adding to existing code can be tricky without introducing subtle changes
  • 50. But this is also good • Makes us really think about which methods will always have a valid object, which will not • Will lead to better API design long term
  • 51. But it can be confusing function myNullableString(input: ?string): number {
 return input.length;
 }
 
 function callerOfMyNullableString(input: string): number {
 return myNullableString(input);
 }

  • 52. function myNullableString(input: ?string): number {
 return input.length;
 }
 
 function callerOfMyNullableString(input: string): number {
 return myNullableString(input);
 }
 input: ?string input: string This is valid
  • 53. This is not valid function myArray(input: Array<?string>): number {
 return input.length;
 }
 
 
 
 
 function callerOfMyArray(input: Array<string>): number {
 return myArrayWithNullableObjects(input);
 }
  • 54. Here’s why function myArray(input: Array<?string>): number {
 input.append(null);
 return input.length;
 } function callerOfMyArray(input: Array<string>): number {
 return myArrayWithNullableObjects(input);
 } No longer valid!
  • 55. Organizational challenges • General organization buy-in • Flow is almost an entirely new language that people need to learn • Working against a moving target • Funny things that happen after merges
  • 56. To recap • We are finding it hard to scale development without types • Adding types to untyped code has a number of challenges, technical and otherwise • We believe the payoff will be totally worth it.
  • 57. Thank you! • Thanks to Kelly, Nick, Gianni for being great teammates and teaching me everything • Thanks to Madeline for organizing this great event! • Image source: unsplash.com
  • 58. Q&A • If you come up with someone, just ask one of us! • Twitter/Medium: @ikai