From side effects to manageable effects

Andrii Melnikov

Some frontend code

var URL = 'https://api.giphy.com/v1/gifs/random?api_key=dc6zaTOxFJmzC&tag=cats';

function app() {
  document.querySelector('button').addEventListener(
    'click',
    () => fetch(URL)
      .then(response => response.json())
      .then(json => json.data.image_url)
      .then(gifSrc => document.querySelector('img').setAttribute('src', gifSrc))
  );
}

Effects

  • DOM: document, setAttribute
  • HTTP: fetch

Key properties of side effects

  • Not a first-class citizen
    • can't be passed as an argument
    • can't be returned from a function
    • can't be assigned to a variable
  • Depend on the "outside world"

What does it mean in practice?

  • Hard to analyse (for humans and tools)
  • Hard to refactor
  • Hard to reuse
  • Hard to test
  • Unpredictable and irreproducible
  • Can't be typed (Flow, TypeScript, etc.)
  • No interactive development (REPL)
  • Hard to guarantee properties of a program
  • Infect side-effect-free code

Hard to analyse

function calcAnything(value) {
  var a = calcA(value);
  var b = calcB(value);
  return calcC(value, b);
}

vs

function doSomething(value) {
  var a = doSomethingA(value);
  var b = doSomethingB(value);
  return doSomethingC(value, b);
}

Computation graph

?

Hard to refactor

function calcAnything(value) {
  var a = calcA(value);
  var b = calcB(value);
  return calcC(value, b);
}

vs

function doSomething(value) {
  var a = doSomethingA(value);
  var b = doSomethingB(value);
  return doSomethingC(value, b);
}
function calcAnything(value) {
  return calcC(value, calcB(value));
}

?

Is this dead code?

Pink Panther

Hard to reuse

function calcLengthAndSum() { ... }

function calcLength(list) {
  return calcLengthAndSum(list).length;
}
function calcMean(list) {
  var res = calcLengthAndSum(list);
  return res.sum / res.length;
}

vs

function sendRequestAndWriteFile() { ... }

function sendRequest() {
  return sendRequestAndWriteFile({ onlyRequest: true });
}
function sendRequestAndWriteFileOnUrl(url) {
  return sendRequestAndWriteFile({ url: url });
}

calcLengthAndSum

sendRequestAndWriteFile

1000 and 1 flags

doSomething({
  sendMetrics: true,
  urlSomeAction: '/action',
  logToFile: './log',
  progressBar: false,
  afterAction: () => ...,
  beforeAction: () => ...
})

Hard to test

it('2 + 2 = 4', () => {
  var result = add(2, 2);
  expect(result).toBe(4);
})
it('remoteAdd send args to endpoint', () => {
  var postCalls = [];
  var fakeRes = {};
  mock(HttpClient, { post: (...args) => {
    postCalls.push(args);
    return fakeRes;
  }})
  var result = remoteAdd(2, 2);
  expect(postCalls.length).toBe(1);
  expect(postCalls[0]).toEqual({url: URL, params: {a: 2, b: 2}});
  expect(result).toBe(fakeRes);
});

Broken testing

 function add(a, b) {
-  return a + b;
+  return {result: a + b};
 }

Test failed: expected 4, received {result: 4}

 function remoteAdd(a, b) {
+  document.dispatchEvent(new LogEvent([a, b]));
   return HttpClient.post({url: URL, params: {a, b}});
 }

Test passed

Some doubts

Some doubts

Solution: explicit dependencies

-function remoteAdd(a, b) {
+function remoteAdd(document, HttpClient, a, b) {
   document.dispatchEvent(new LogEvent([a, b]));
   return HttpClient.post({ url: URL, params: {a, b} });
 }

Angular DI

DI is the opium of developers

 function remoteAdd(HttpClient, a, b) {
+  HttpClient.options({url: URL, params: {a, b}})
   return HttpClient.post({ url: URL, params: {a, b} });
 }

Bad:

var result = remoteAdd(HttpClient, a, b)
expect(result).toEqual(output)
expect(HttpClient.post.mock.calls)
  .toEqual(postCalls)

Good:

var world = new World()
var result = remoteAdd(world, a, b)
expect(result).toEqual(output)
expect(world.changes()).toEqual(sideEffects)

Unpredictable and irreproducible

Everything changes and nothing stands still

— Heraclitus

add(2, 2);

vs

try {
  remoteAdd(2, 2);
} catch (e) {
  handleError(e);
}
calc(a, b) === calc(a, b)

vs

var res1 = fetchSomething(a);
// data on the server changed
var res2 = fetchSomething(a);
res1 !== res2

Can't be typed

undefined is not a function

Can't be typed

function parse(str: string): number | null {
  return isLikeNumber(str) ? parseInt(str) : null;
}
function add(a: number, b: number) {
  return a + b;
}
add(parse('aaa'), 3) // compile-time error

But types don't help with effectful code:

function patchDOM(patch: DOMPatch): void { ... }
function serverProgram() {
  ...
  patchDOM(patch); // run-time error
}

Solution?

A possible solution in Flow

type DB = { type: 'DB' };
type User = { username: string, uid: number };
function createUser(username: string): Eff<{ write: DB }, User> { ... }
function lookupUser(username: string): Eff<{ read: DB }, ?User> { ... }

No interactive development

Tools:

  • REPL (terminal, editor plugin, console)
  • Mancy
  • Light Table

Interactive development — Nikita Prokopov

Light Table

Problems

> deleteUser(12)
{result: "OK"}

> deleteUser(12)
{error: "User not found"}

> addUser(12, data)

> deleteUser(12)
{result: "OK"}

Possible solutions:

  • jest-repl
  • mocha debug REPL

Hard to guarantee properties

Side-effect-free functions have properties — like math functions:

var sortIdempotent =
  jsc.forall("string -> nat", "array string", function (f, arr) {
    return _.isEqual(_.sortBy(_.sortBy(arr, f), f), _.sortBy(arr, f));
  });

jsc.assert(sortIdempotent);

Tools: testcheck, jsverify

Two ways of programming

The knight at the crossroads

Top-down

  1. Vision and design
printSum(list: Array): PrintedSumToScreenEffect
  1. Development
sum(list: Array): number
printToScreen(value: number): PrintedSumToScreenEffect

Tools:

  • tests — provable, but not general
  • diagrams (UML etc.) — general, but not provable
  • static types — general and provable

People draw UML diagrams to understand the overall structure of a program. That's exactly what Haskell programmers do when they come up with type signatures.

— Simon Peyton Jones

Bottom-up

  1. Reuse and modularise
sum(1, 2, 3, 4)
// -> 10
print('Hello', screen)
// -> prints 'Hello' to screen
  1. Solution
function printSum(list) {
  print(sum(...list), screen)
}

Tools:

  • tests — fragile and slow (not interactive)
  • REPL — fast and agile

Two ways…

Top-down

Top-down

  • Define the top-level API (no implementation)
  • Define the underlying API

More consistent and correct, but slower and less agile.

Main tool: strong static types

Bottom-up

Bottom-up

  • Implement low-level calls as isolated components
  • Combine them into a higher-level API

More agile and fast, but less consistent.

Main tool: REPL

…or no way?

No way

Infects side-effect-free code

function calcForItem(...) {
  ...
  var cachedResult = localStorage
    .getItem(argsHash);
  if (cachedResult) {
    return cachedResult;
  } else {
    ...
    localStorage.setItem(argsHash, res)
    return res;
  }
}

Pure to impure

Ice-nine for source code

Cat's Cradle

“Have you read Cat's Cradle?”

“No.”

“In that novel the world ends because of a molecule that turns any water it touches into ice. All the waters of the world are connected — pond, stream, river, lake, ocean — so the whole world freezes. The molecule is called ice-nine.”

Two kinds of computation

Implicit execution:

> var user = requestUser();
{ fio: "Ivan Ivanov", age: 19 }
> var res = writeToFile(user.fio);
{ success: true }

Explicit execution:

> var req = requestUser();
{ type: "http", url: "/user", payload: {id: 2} }
> var user = runEffect(req);
{ fio: "Ivan Ivanov", age: 19 }
> var writing = writeToFile(user.fio);
{ type: "file", name: "./sys.log", data: "Ivan Ivanov" }
> var res = runEffect(writing)
{ success: true }

Pure vs effectful

Pure:

var res1 = doSmth1(start);
var res2 = doSmth2(res1);
var res3 = doSmth3(res2);

With effects:

var eff1 = doSmth1(start);
var res1 = runEffect(eff1);
var eff2 = doSmth2(res1);
var res2 = runEffect(eff2);
var eff3 = doSmth3(res2);
var res3 = runEffect(eff3);

Sync vs async

Sync:

var res1 = doSmth1(start);
var res2 = doSmth2(res1);
var res3 = doSmth3(res2);

Async:

doSmth1(res1 => {
  doSmth2(res1, res2 => {
    doSmth3(res2);
  });
});

Safe vs error handling

Without errors:

var res1 = doSmth1(start);
var res2 = doSmth2(res1);
var res3 = doSmth3(res2);

With error handling:

var res1 = doSmth1(start);
if (!isError(res1)) {
  var res2 = doSmth2(res1);
  if (!isError(res2)) {
    var res3 = doSmth3(res2);
  } else { handle(res2) }
} else { handle(res1) }

Non-nullable vs nullable

Non-nullable:

var res1 = doSmth1(start);
var res2 = doSmth2(res1);
var res3 = doSmth3(res2);

With null checks:

var res1 = doSmth1(start);
if (!isNull(res1)) {
  var res2 = doSmth2(res1);
  if (!isNull(res2)) {
    var res3 = doSmth3(res2);
  }
}

Control flow

In computer science, control flow (or flow of control) is the order in which individual statements, instructions or function calls of an imperative program are executed or evaluated.

— Wikipedia

Control-flow primitives:

  • if
  • switch … case
  • while, for
  • { some code }
  • break, continue
  • throw new Error()
  • return res, yield res

GOTO

GOTO

GOTO example

Example: error handling

Today:

var res1 = doSmth1(start);
if (!isError(res1)) {
  var res2 = doSmth2(res1);
  if (!isError(res2)) {
    var res3 = doSmth3(res2);
  } else { handle(res2) }
} else { handle(res1) }

With GOTO:

error:
  handle(errorMsg)

global errorMsg;
function exitIfErr(res) {
  if (isError(res)) {
    errorMsg = res;
    goto error;
  } else {
    return res;
  }
}
// calculation
var res1 = exitIfErr(doSmth1(start));
var res2 = exitIfErr(doSmth2(res1));
var res3 = exitIfErr(doSmth3(res2));

Don't forget where you came from

The mother of all statements: if value then goto label

i = 1;
while (i < 4) {
  print(i);
  i = i + 1;
}
i = 1
START: if i = 4 then goto END
  print(i)
  i = i + 1
  goto START
END:
Turing machine

All you need is…

Calculation:

c = add(inc(a), dec(b))

Order of execution:

  1. inc(a), dec(b)
  2. add(inc(a), dec(b))

Conditional jump:

if add(a, b) then goto LABEL

Order of execution:

  1. add(a, b)
  2. if (add(a, b))
  3. goto LABEL

New World Order

Imagine a calculation evaluated in reverse order: c = add(inc(a), dec(b))

  1. add(placeholder1, placeholder2)
  2. inc(a)
  3. dec(b)

if(a, goto label)

  1. if(placeholder1, placeholder2)
  2. a
  3. maybe goto label

In your code

var x = {}
x && x.obj && x.obj.prop

var x = {}
and(and(x, x.obj), x.obj.prop)

This is the norm

Normal order a.k.a. call-by-name (call-by-need) a.k.a. lazy evaluation. Our languages aren't Turing-complete without it.

Theorem: every computation can be carried out in normal order.

The first "programming languages", 1936:

  • Alonzo Church — lambda calculus — normal order
  • Alan Turing — Turing machine — applicative order

The first computers, 1944: von Neumann architecture (inspired by the Turing machine)

With applicative order: everything is calculation + control flow

With normal order: everything is calculation

Control flow as continuation

Continuation-passing style:

Async:

requestUser(user => {
  writeToFile(user.fio,
    res => { ... }
  )
})

Errors:

doWithErrors(res => {
  doWithErrors2(
    res,
    res2 => { ... },
    handleErr
  )
}, handleErr)

Introducing call/cc

var a = 1 + 2;
var b = a + 4 // 7
var firstCalc = cont => cont(1 + 2)
var b = firstCalc(a => a + 4) // 7

cont === a => a + 4
var r
var a = callcc(cont => {
  r = cont;
  cont(1 + 2) // 7
  return 1 + 2
});
var b = a + 4 // 7
r(1 + 2) // 7

Exceptions

var cont;
function throw(err) {
  cont(err);
}
function try(program, handleErr) {
  var res = callcc(c => {
    cont = c;
    program()
  })
  if (isError(res)) {
    handleErr(res)
  }
}

try(
  () => {
    var a = doWithErrors() // throw new Error()
    ...
  },
  err => { ... }
)

Implementing exceptions with continuations

Algebraic effects

var cont, currCont
function perform(effect) {
  return callcc(c => {
    currCont = c;
    return cont(effect);
  })
}
function run(program, handleEffect) {
  var res = callcc(c => {
    cont = c;
    program()
  })
  if (isEffect(res)) {
    currCont(handleEffect(res))
  }
  return res;
}
run(
  () => {
    var user = perform(requestUser())
    var fio = user.fio
    var res = perform(writeToFile(fio))
  },
  eff => runEffect(eff)
)

Algebraic effects on es-discuss

Continuations as a precursor of

  • exceptions
  • algebraic effects with handlers
  • generators
  • fibers
  • coroutines

Control flow as higher-order calculation

writeToFile(requestUser().fio)
// vs
pipe(() => requestUser(), x => x.fio, fio => writeToFile(fio))

From execution to calculation, a.k.a. thunk:

requestUser() → () => requestUser()

Thunks are lazy!

Fixing the NPE

x && x.obj && x.obj.prop

function pipe(...fns) {
  return value => {
    var res = value
    fns.forEach(currFn => {
      res = currFn(res)
    })
    return res
  };
}

pipe(
  x => x.obj,
  obj => obj.prop
)(x)
function pipeWithNullable(...fns) {
  return value => {
    var res = value;
    fns.forEach(currFn => {
      if (!isNil(res)) {
        res = currFn(res)
      }
    })
    return res
  };
}

pipeWithNullable(
  x => x.obj,
  obj => obj.prop
)(x)

Let's make a great interface

x && x.obj && x.obj.prop

class Option {
  constructor(value) {
    this.value = value
  }
  then(fn) {
    return isNil(this.value)
      ? this
      : new Option(fn(this.value))
  }
}
var x = {};
var val = new Option(x)
  .then(x => x.obj)
  .then(obj => obj.prop)

The main battle!

class IO {
  constructor(calc, args = []) {
    this.calc = calc
    this.args = args
  }
  then(fn) {
    return new IO(fn, [this])
  }
}
var ioAction = new IO(requestUser)
  .then(x => x.fio)
  .then(fio =>
    new IO(() => writeToFile(fio))
  )

run(ioAction)
ioAction = {
  calc: fio => new IO(() => writeToFile(fio)),
  args: [
    {
      calc: x => x.fio,
      args: [
        { calc: requestUser, args: [] }
      ]
    }
  ]
}

Representing monads

  • of, pure, unit — constructor. How do we wrap a value into a monad?
  • flatMap, bind, chain — applier. How do we unwrap a value from a monad?

Monad laws:

  • Left identity: flatMap(f, of(x)) ≡ f(x)
  • Right identity: flatMap(of, m) ≡ m
  • Associativity: flatMap(g, flatMap(f, m)) ≡ flatMap(x => flatMap(g, f(x)), m)

Don't break the laws! Beware of the Haskell police!

Monads are everywhere!

  • Promise a.k.a. Task a.k.a. Future
  • Optional a.k.a. Option a.k.a. Maybe
  • List
  • Either a.k.a. Try a.k.a. Error
  • Observable

Two ways?

Monads and continuations are isomorphic and equally powerful — Representing Monads

They're just representations of control flow.

Control flow is born from the incompleteness of strict (applicative) evaluation — Lazy Evaluation and Delimited Control

A journey of a thousand miles begins with a single step

Origins

Plato's cave

Plato's cave

A third way?

Message passing as the foundation of OOP:

Message passing as the foundation of concurrent computation:

Modern frontend frameworks are built on message passing:

  • store in Flux, Redux, ngrx/store
  • computed in MobX, Vue, Ember
  • EventEmitter in Angular
  • subscriptions and Cmd in Elm

…and so is the backend:

  • actors in Akka, Erlang, Elixir
  • channels in Go
  • Reactive Streams in Spring

Two-colour language

In Soviet Russia, side effects control you!

blue•function doSomethingAzure() {
  // This is a blue function...
}
red•function doSomethingCarnelian() {
  // This is a red function...
}

blue•function doSomethingAzure() {
  doSomethingCarnelian()•red;  // Error — you can't call red inside blue
}

Two different kinds of program code:

  • execution (side effects) — red functions
  • calculation (pure) — blue functions

Bob Nystrom's article · Andrey Salomatin's talk

← Andrii MelnikovFrom side effects to manageable effectsarticlevideo ↗1 / 56