Slide 1

Slide 1 text

JavaScript API Hall of Shame @ariyahidayat April 30, 2014

Slide 2

Slide 2 text

/usr/bin/whoami shapesecurity.com

Slide 3

Slide 3 text

.setState( ); treeItem true, false

Slide 4

Slide 4 text

https://twitter.com/AriyaHidayat/status/455892955765551105

Slide 5

Slide 5 text

“How to Design a Good API and Why It Matters” Joshua Bloch “Qt API Design Principles” http://qt-project.org/wiki/API-Design-Principles Matthias Ettrich, Jasmin Blanchette

Slide 6

Slide 6 text

https://twitter.com/AriyaHidayat/status/429111596627918848

Slide 7

Slide 7 text

Modular Application Architecture Module A Module B interface

Slide 8

Slide 8 text

WHY? Nobody reads API documentation Code is written once, read many times

Slide 9

Slide 9 text

Readable, consistent, crystal clear Thank you, Captain Obvious!

Slide 10

Slide 10 text

Using static polymorphism to ensure consistency Preventing dangerous convenience such as Boolean trap Avoiding unreadable code due to confusing semantics

Slide 11

Slide 11 text

Static Polymorphism

Slide 12

Slide 12 text

X1.value = 'Rare'; X2.value = 'Medium'; X3.value = 'Well done'; Y.option = 'Fries'; Z.caption = 'Order'; X1.value = 'Rare'; X2.value = 'Medium'; X3.value = 'Well done'; Y.value = 'Fries'; Z.value = 'Order'; http://ariya.ofilabs.com/2014/03/api-names-and-static-polymorphism.html

Slide 13

Slide 13 text

slider.maxValue = 100; slider.minValue = 0; slider.value = 34; indicator.range = [100, 0]; indicator.progress = 61; slider.maximum = 100; slider.minimum = 0; slider.value = 34; indicator.maximum = 100; indicator.minimum = 0; indicator.value = 61;

Slide 14

Slide 14 text

point.translate(14, -3) rect.translateBy(26, 4) point.translate(14, -3) rect.translate(26, 4)

Slide 15

Slide 15 text

corner = new Point(10, 10); dim = new Size(70, 50); R = new Rect(corner, dim); Q = new Rect(10, 10, 80, 60); corner = new Point(10, 10); dim = new Size(70, 50); R = new Rect(corner, dim); Q = new Rect(10, 10, 70, 50); corner dimension x1, y1, x2, y2 x, y, w, h http://ariya.ofilabs.com/2014/03/api-names-and-static-polymorphism.html

Slide 16

Slide 16 text

var x = NaN; isNaN(x) true x === NaN false https://twitter.com/AriyaHidayat/status/393034774245171200

Slide 17

Slide 17 text

GarlicNaN != NaN ES 7

Slide 18

Slide 18 text

Convenience & Traps

Slide 19

Slide 19 text

What’s in a name? that which we call a rose by any other name would smell as sweet... Romeo and Juliet Act II. Scene II

Slide 20

Slide 20 text

Can We Have Some Vowels, Please? BrCtl → WebView

Slide 21

Slide 21 text

DOM Event event.initKeyEvent("keypress", true, true, null, null, false, false, false, false, 9, 0);

Slide 22

Slide 22 text

Boolean Trap // Horizontal s1 = new Slider(true); // Vertical s2 = new Slider(false); s1 = new Slider({ orientation: 'horizontal' }); s2 = new Slider({ orientation: 'vertical' });

Slide 23

Slide 23 text

Boolean Modifier Trap // Animate the resize w.resize(250, 150, true); // Do not animate the resize w.resize(250, 150, false); w.resize(250, 150, { animate: true });

Slide 24

Slide 24 text

Ping-pong, Anyone? // Expand + animate treeItem.setState(true, true); // Expand + don't animate treeItem.setState(true, false); // Collapse + animate treeItem.setState(false, true);

Slide 25

Slide 25 text

https://twitter.com/ID_AA_Carmack/status/367485612627984385

Slide 26

Slide 26 text

Ambiguity Begets Insanity

Slide 27

Slide 27 text

Double Negatives X.disabled = false; Y.setHidden(true); filter.caseInsensitive = true; X.enabled = true; Y.setVisible(false); filter.caseSensitive = false;

Slide 28

Slide 28 text

cube.translucency = 0.2; 20% translucent cube.opacity = 0.8; 80% opaque

Slide 29

Slide 29 text

Nonverbal Actions status.message("Ready"); page.forward(); page.backward(); status.showMessage("Ready"); page.goForward(); page.goBackward();

Slide 30

Slide 30 text

picker.yearFrom = 1980; picker.yearTo = 2020; picker.minimumYear = 1980; picker.maximumYear = 2020;

Slide 31

Slide 31 text

this.callMe = "Adam"; flight.from = SFO; flight.to = JFK; this.name = "Adam"; flight.departure = SFO; flight.destination = JFK;

Slide 32

Slide 32 text

String Extraction 'forcedotcom2014'.substr(5, 6) "dotcom" 'forcedotcom2014'.substr(6, 5) "otcom" 'forcedotcom2014'.substring(5, 6) "d" 'forcedotcom2014'.substring(6, 5) "d" 'forcedotcom2014'.slice(5, 6) "d" 'forcedotcom2014'.slice(6, 5) "" http://ariya.ofilabs.com/2014/02/javascript-string-substring-substr-slice.html

Slide 33

Slide 33 text

Array Extraction var a = [14, 3, 77] var b = a.slice(1, 2) a [14, 3, 77] b [3] var a = [14, 3, 77] var b = a.splice(1, 2) a [14] b [3, 77] Immutable vs Mutable http://ariya.ofilabs.com/2014/02/javascript-array-slice-vs-splice.html

Slide 34

Slide 34 text

Verb = Action var p = new Point(14, 3); p.translate(4, 4); Does this change my string or return a fresh new string? var s = ' hal9000 '; s.trim();

Slide 35

Slide 35 text

Explicit (Im)mutability var p = new Point(14, 3); p.translate(4, 4); p.translated(4, 4); var s = ' hal9000 '; s.trim(); s.trimmed(); p does not change Returns a translated version of p

Slide 36

Slide 36 text

Best Practices

Slide 37

Slide 37 text

No content

Slide 38

Slide 38 text

#1: Private by Default Public = Irreversible

Slide 39

Slide 39 text

-- yours truly “You’d fail your first two attempts anyway.”

Slide 40

Slide 40 text

SHStripMneumonic “Why is the function SHStripMneumonic misspelled?” Raymond Chen, Microsoft http://blogs.msdn.com/b/oldnewthing/archive/2008/05/19/8518565.aspx

Slide 41

Slide 41 text

No content

Slide 42

Slide 42 text

“Write 3 examples which use the API” #2: Public by Justification

Slide 43

Slide 43 text

No content

Slide 44

Slide 44 text

#3: Mandatory API Review

Slide 45

Slide 45 text

“YOU SHALL NOT PASS!” — Darth Vader

Slide 46

Slide 46 text

#4: API Tools Tools separate us

Slide 47

Slide 47 text

API Detective

Slide 48

Slide 48 text

T D D B D D P D D

Slide 49

Slide 49 text

Syntax Parser var answer = 42 keyword equal sign identifier number Variable Declaration Identifier Literal Constant Tokenization → Tokens Parsing → Syntax Tree

Slide 50

Slide 50 text

{ type: "Program", body: [ { type: "VariableDeclaration", declarations: [ { type: "VariableDeclarator", id: { type: "Identifier", name: "answer" }, init: { type: "Literal", value: 42, raw: "42" } } ], kind: "var" } ] } Syntax Tree var answer = 42; Terms → ECMAScript 5.1 Specification https://developer.mozilla.org/en-US/docs/SpiderMonkey/Parser_API

Slide 51

Slide 51 text

Syntax Visualization http://esprima.org/demo/parse.html

Slide 52

Slide 52 text

Module Structure MyApp.create('MyApp.Person', { name: 'Joe Sixpack', age: 42, constructor: function(name) {}, walk: function(steps) {} run: function(steps) {} }); { objectName: 'MyApp.Person', functions: ['walk', 'run'], properties: ['name', 'age'] } Metadata Meta-object

Slide 53

Slide 53 text

Collecting Member Expression foo.bar syntax = esprima.parse(code); traverse(syntax, function (node) { if (node.type === 'MemberExpression') { if (node.property) { console.log(node.property.name); } } });

Slide 54

Slide 54 text

Detecting Boolean Traps reload(x, y, false) function checkLastArgument(node) { var args = node['arguments']; if (args.length < 2) { return; } if (typeof args[args.length - 1].value === 'boolean') { report(node, 'Dangerous Boolean literal'); } }

Slide 55

Slide 55 text

Blacklisting Function Names setDisabled(false) This block is left intentionally blank. Exercise for the brave reader!

Slide 56

Slide 56 text

Future API-Cop “You call this immutable function, yet you never use its return value.” “You check the return value of this function 2000 times. Why don’t you do it this time (line = ….)?”

Slide 57

Slide 57 text

Final Words Practice the rituals: ● Apply static polymorphism ● Judge every convenient shortcut ● Read aloud (and often) Build, write, tweak API tools Apply best practices

Slide 58

Slide 58 text

Thank You @ariyahidayat ariya.ofilabs.com speakerdeck.com/ariya Some artworks are from http://openclipart.org.