Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Technical terms I didn’t understand, then decided to find out.

Technical terms I didn’t understand, then decided to find out.

At times when you are reading a tweet or an article you come across words and phrases like "idempotence", "idiomatic", "imperative vs declarative", "soundness", "lexical scope", and “impedance mismatch”.

I used to struggle with the meaning of these terms so I decided to finally find out what they mean and I wish to share what I've learned by showing code samples and pictures. I believe this is the best way to understand a concept.

620ecdb7215ec072617bfd7f75c98760?s=128

Nikhil Verma

May 28, 2019
Tweet

Transcript

  1. Technical terms I didn’t understand, then decided to find out.

    @NikhilVerma #LondonJS
  2. Nikhil Verma Core Team Lead Frontend Team @NikhilVerma

  3. None
  4. Often times I got a bit lost when reading things

    online… 4
  5. 5

  6. I collected these terms overtime and asked my colleagues to

    contribute. We came up with this list 6
  7. imperative / declarative - call tree - cardinality - coersion

    - constraint solver - idempotence - covariant / invariant - dependency injection - dynamic scoping - idiomatic - function shadowing - generics - inference - lexical scope -
 inversion of control - algebraic subtyping - implicit subtyping - type - control flow - semantics - side effects - state machine - 
 impedance mismatch - leaky abstraction - macro - meta languages - meta programming - monad - paradigm - parametric polymorphism -
 nominal / structured typing - persistent identity - primitives - reconciler - 
 strongly / weakly typed - reflection - stack frame - syntactic sugar - 
 type soundness - tight or loose coupling - temporal dead zone - virtual structs - 7
  8. Today we’ll talk about General Programming • imperative / declarative

    • idempotence • idiomatic • inversion of control • impedance mismatch Types • nominal / structured typing • strongly / weakly typed • type soundness 8
  9. imperative / declarative 9

  10. Part of “programming paradigms” Generally speaking • imperative - “You

    tell the machine exactly what to do” • declarative - “You tell the machine your expectations” https://en.wikipedia.org/wiki/Programming_paradigm 10
  11. 11

  12. imperative function returnOdd(arr) { const odds = []; for (var

    i = 0; i < arr.length; i++) { const num = arr[i]; if (num % 2 !== 0) { odds.push(num); } } return odds; } 12
  13. declarative function returnOdd(arr) { return arr.filter(num => num % 2

    !== 0); } 13
  14. Let’s look at something a bit different 14

  15. imperative const selectedRecords = []; for (let idx = 0;

    idx < records.length; idx++) { if (selectedRecords.length === 10) { return selectedRecords; } if (records[idx].id < 100) { selectedRecords.push(records[idx]); } } return selectedRecords; 15
  16. declarative SELECT * from records WHERE id < 100 LIMIT

    10; 16
  17. 17 Imperative Declarative • Verbose • Explains how it works

    internally • Complete control over the flow of the code • Suitable where direct control of machine is priority • Terse • Inner functionality is abstracted away • Little control over how the code is executed • Suitable when human readability is priority
  18. idempotence 18

  19. idempotence Something which can be done several times without affecting

    the outcome. 5 * 1 = 5 5 * 1 * 1 = 5 5 * 1 * 1 * 1 = 5 5 * 1 * 1 * 1 * 1 = 5 5 * 1 * 1 * 1 * 1 * 1 = 5 https://en.wikipedia.org/wiki/Idempotence 19
  20. idempotency in programming • Utility function being called • User

    clicking on a button to submit a form • What if it’s a payment form? • What if it’s a chat message? • Calling an API endpoint http://cloudingmine.com/idempotence-what-is-it-and-why-should-i-care/ 20
  21. not idempotent class RegistrationPage extends React.Component { registerUser() { api.registerUser(this.state).then(this.navigateToApp);

    } render() { return <Button onClick={this.registerUser} />; } } 21
  22. idempotent class RegistrationPage extends React.Component { registerUser() { if (this.isRegistering)

    { return; } this.isRegistering = true; api.registerUser(this.state).then(this.this.navigateToApp); } render() { return <Button onClick={this.registerUser} />; } } 22
  23. What does it mean for you? Whenever writing code, consider

    if it should be idempotent or not. Often times it’s about keeping actions stateful. 23
  24. idiomatic 24

  25. idiomatic “Follow the conventions of the technology.” 25

  26. not idiomatic function multiply(arr, number) { const newArr = [];

    for (var i = 0; i < arr.length; i++) { newArr.push(arr[i] * number); } return newArr; } 26
  27. idiomatic function multiply(arr, number) { return arr.map(arrNum => arrNum *

    number); } 27
  28. 28 https://twitter.com/v8js/status/1040219491358179328

  29. “The performance of Map is much better than Object to

    implement dictionaries when they contain a large amount of entries, which is usually what we have here. After testing this change in Facebook we've seen a ~20% reduction of the time to run all tests …” https://github.com/facebook/jest/pull/6960/files 29
  30. So what does it mean for you? • Idiomatic code

    should be preferred • It will help others understand your code better. • It will help library authors and language maintainers to optimise for the most used cases • Idioms evolve! What was idiomatic a year ago might not be the same today. 30
  31. inversion of control 31

  32. inversion of control In the simplest terms: • traditional flow

    of control - “I want these items!” • inversion of control - “Give me those items!” https://en.wikipedia.org/wiki/Inversion_of_control 32
  33. An example of inversion of control in JS 33 callbacks!

  34. callbacks // MyCode.js fetch(API_ENDPOINT) .then(data => data.json()) .then(handleResponse); // “I

    will send you the API response” function handleResponse(apiResponse) { // “Give me the apiResponse” // do something with the response } // MyTest.js const response = { ...mockResponse }; handleResponse(response); 34
  35. dependency injection 35

  36. no dependency injected import api from './api'; export class Session

    { loginUser() { api.loginUser().then(this.doSomething); } } 36
  37. dependency injection export class Session { constructor(api) { super(); this.api

    = api; } loginUser() { this.api.loginUser().then(this.doSomething); } } 37
  38. dependency injection // Easier to mock API import mockApi from

    './mockApi'; const session = new Session(mockApi); session.loginUser(); // Easier to reuse import myCustomAPI from './myCustomAPI'; const session = new Session(myCustomAPI); session.loginUser(); 38
  39. a component example 39

  40. no dependency injected import BackButton from './BackButton'; function NavigationBar({ hasBack

    }) { return ( <div> { hasBack ? <BackButton /> : null } {/* rest of the implementation */} </div> ); } <NavigationBar hasBack={true} /> 40
  41. dependency injected component function NavigationBar({ leftSlot }) { return (

    <div> { leftSlot ? leftSlot : null } {/* rest of the implementation */} </div> ); } import BackButton from './BackButton'; <NavigationBar leftSlot={<BackButton />} /> 41
  42. dependency injected component import BackButton from './BackButton'; <NavigationBar leftSlot={<BackButton />}

    /> 42
  43. dependency injected component import CloseButton from './CloseButton'; <NavigationBar leftSlot={<CloseButton />}

    /> 43
  44. dependency injected component import TestButton from './TestButton'; <NavigationBar leftSlot={<TestButton />}

    /> 44
  45. So what does it mean for you? Inversion of control

    techniques can make your code: • Modular • Testable • Reusable • Flexible Consider if you should use it when writing your code. 45
  46. impedance mismatch 46

  47. impedance mismatch In simple terms it is a mismatch between

    what you want and what you have. e.g. 1. You want to render the name and online status of a user. 2. But those things lie on different APIs and in different formats. 3. So you must fetch both and assemble a final result together. https://devblogs.microsoft.com/oldnewthing/20180123-00/?p=97865 https://haacked.com/archive/2004/06/15/impedance-mismatch.aspx/ 47
  48. high impedance mismatch Promise.all([ api.get(GET_PERSON_PROFILE, { userId: '1234' }), api.get(GET_PERSON_STATUS,

    { userId: '1234' }) ]).then(([ personProfile, personStatus ]) => { this.setState({ name: personProfile.data.name, isOnline: personStatus.data.status === 'ONLINE' }); }); 48
  49. low impedance mismatch api.get(GET_USER, { userId: '1234', fields: ['name', 'isOnline']

    }) .then(({ name, status }) => { this.setState({ name, isOnline }); }); 49
  50. GraphQL query HeroNameAndFriends { hero { name friends { name

    } } } https://graphql.org/learn/queries/#operation-name 50 { "data": { "hero": { "name": "R2-D2", "friends": [ { "name": "Luke Skywalker" }, { "name": "Han Solo" } ] } } }
  51. So what does it mean for me? • Impedance mismatch

    happens because of the nature of server/client technologies used. • We should strive to lower the impedance mismatch because it makes us efficient. https://overreacted.io/making-setinterval-declarative-with-react-hooks/ - Our “impedance mismatch” is not between Databases and Objects. It is between the React programming model and the imperative setInterval API. 51
  52. nominal / structured typing 52

  53. nominal / structured typing In general terms: • nominal -

    “validate this type based on it’s name” • structured - “validate this type based on it’s shape” https://en.wikipedia.org/wiki/Nominative_and_structural_type_systems 53
  54. nominal typing class Foo { method(input: string): number { ...

    } } class Bar { method(input: string): number { ... } } let foo: Foo = new Bar(); // ERROR!! 54
  55. structured typing class Foo { method(input: string): number { ...

    } } class Bar { method(input: string): number { ... } } let foo: Foo = new Bar(); // OKAY!! TypeScript example 55
  56. structured typing class Foo { method(input: string): number { ...

    } } class Bar { method(input: string): boolean { ... } } let foo: Foo = new Bar(); // ERROR!! 56
  57. Is structured typing better? 57

  58. class Student { id: string; constructor(id: string) { this.id =

    id; } delete() { /* delete this.id */ } } class Teacher { id: string; constructor(id: string) { this.id = id; } delete() { /* delete this.id */ } } // In this file let teacher = new Teacher('5'); // In some other file function deleteStudent(student: Student): void { student.delete(); } deleteStudent(teacher); // Whoops! 58
  59. 59 Nominal Structured • Rigidity • Simplicity • Flexibility •

    Complexity https://github.com/Microsoft/TypeScript/issues/202#issuecomment-329914167 https://flow.org/en/docs/lang/nominal-structural/ One language can have both nominal and structural typing! e.g. in Flow Classes are nominal but objects are structured
  60. strongly / weakly typed 60

  61. strongly / loosely typed 61

  62. strongly / loosely typed In simple terms, ”strongly typed languages

    have stricter type checks compared to loosely typed languages.” https://en.wikipedia.org/wiki/Strong_and_weak_typing 62
  63. Things which determine strong/loose • Implicit type conversions • Static

    type-checking • Dynamic type-checking https://en.wikipedia.org/wiki/Strong_and_weak_typing#Definitions_of_%22strong%22_or_%22weak%22 63
  64. implicit type conversion var num = 5; var str =

    '6'; var obj = {}; var sum = num + str; // "56" var minus = num - str; // -1 var mult = num * str; // 30 var objSum = obj + sum; // "[object Object]56" var objMult = obj * num; // NaN 64
  65. static type checking var num = 5; var str =

    '6'; var obj = {}; var sum = num + str; // "56" var minus = num - str; // TYPE ERROR var mult = num * str; // TYPE ERROR var objSum = obj + num; // TYPE ERROR var objMult = obj * num; // TYPE ERROR 65
  66. dynamic type checking var item = 'str'; console.log(`${item}_hello`); // "str_hello"

    item = NaN; if (isNaN(item)) { console.log('NaN!'); // "NaN!" } item = { hello: 'world' } console.log(typeof item); // object 66
  67. 67 Strongly Typed Loosely Typed • Strictness • Favour errors

    at compile time • Typically more boilerplate (*) • Flexibility • Favour errors at runtime • Typically less boilerplate * Languages with good type inference can still remain terse (e.g. ReasonML) https://en.wikipedia.org/wiki/Type_system#Static_and_dynamic_type_checking_in_practice
  68. type soundness 68

  69. What is type soundness? Type soundness is the guarantee of

    a language that a “given type will always be the same at runtime.” 69
  70. TypeScript (not sound) function addInteger(arr: Array<string | number>): Array<string |

    number> { return arr.concat(3); } const strings: Array<string> = ['foo', 'bar']; addInteger(strings); TS Playground 70
  71. Reason (sound) let addInteger = (arr) => Array.append(arr, [| 4

    |]); let strings: array(string) = [| "foo", "bar" |]; addInteger(strings); ReasonML Playground 71
  72. Wait, why would any typed language want to be unsound?

    72
  73. Soundness isn’t always the end-goal https://github.com/Microsoft/TypeScript/wiki/TypeScript-Design-Goals 73

  74. Soundness vs Unsoundness 74

  75. Soundness vs Completeness 75

  76. 76 Soundness Completeness “Any code that can be typed is

    valid” • Rigidity • If the code compiles it will not fail at runtime “Any code that is valid can be typed” • Flexibility • If the code compiles it can fail at runtime https://en.wikipedia.org/wiki/Soundness https://en.wikipedia.org/wiki/Completeness_(logic) https://news.ycombinator.com/item?id=16780068
  77. What I learnt General Programming • imperative / declarative -

    “Telling the machine / expecting results” • idempotence - “Can be done many times without effecting the outcome” • idiomatic - “Follow the conventions of the technology.” • inversion of control - “Give me those dependencies” • impedance mismatch - “What you want vs what you have” Types • nominal / structured typing - “Validate based on name / structure” • strongly / loosely typed - “Stricter checks / relaxed checks” • type soundness - “Guarantee that a type will remain the same always” 77
  78. How I went about learning them 1. Started with Wikipedia

    2. Googled for articles or blog posts 3. Find out experts in the field and read about what they 4. Searched Twitter/Hacker News for those terms and followed the discussion thread 5. Search, Rinse and Repeat 78
  79. Thank you for listening! 79 DM me if you have

    any feedback @NikhilVerma