BattlefyBlogHistoryOpen menu
Close menuHistory

Code is multicoloured

Ronald Chen June 27th 2022

Img

Code is coloured in many different ways. Coloured code have restrictions on how it can interact with code of a different colour.

For example, consider JavaScript async code,

  • synchronous function that calls synchronous function remains synchronous
  • synchronous function that calls async function becomes async
  • async function that calls async function remains async
  • async function that calls synchronous function remains async

We say code is has two different colours async and synchronous.

Since async/await are promises and promises are monad, does this mean all monads colour code?

Yes!

Consider the Option monad. It remains coloured while passing around Some/None values, but can also become uncoloured.

Example of Option monad in Scala,

val value: Integer = 42

// start Option colouring
val x: Option[Integer] = Some(value)

val even: Option[Boolean] = for {
  valueInsideX <- x
} yield valueInsideX % 2 == 0

val result: String = even match {
  case Some(true)  => "number is even"
  case Some(false) => "number is odd"
  case None        => "missing number"
}
// end Option colouring

println(result) // prints: number is even

Similarly in Haskell IO is a monad that colours a program.

Since Haskell IO is isolating the side-effects of IO from pure functions, does this mean function purity colours code?

Yes!

Function purity has yet another set of colouring rules,

  • pure function that calls pure function remains pure
  • pure function that calls impure function becomes impure
  • impure function that calls impure function remains impure
  • impure function that calls pure function remains impure

Notice how these are the same rules as synchronous/async function, yet it is a different colouring.

There are so many other forms of colouring,

  • DOM event listeners are coloured
  • requestAnimationFrames are coloured
  • JavaScript type="module" vs type="script" are coloured. Modules import other modules declaratively, but scripts import other modules with dynamic import.
  • Web Workers are coloured and threading in general is coloured. Notice how multi-threading always requires special constructs to share memory either by message passing or atomics/synchronization?
  • puppeteer evalulates are coloured since the calling Node.js JavaScript context is different the running Chrome Browser JavaScript context.

Programming is postmodern art

Different colourings are mostly independent which makes code very confusing very fast. If one tries to optimize for one type of colouring, often it ruins the colouring of another. Everything becomes a huge tradeoff.

Can you skillfully navigate coloured code? We’re like to hear from you, Battlefy is hiring.

2024

  • MLBB Custom Lobby Feature
    Stefan Wilson - April 16th 2024

2023

2022

Powered by
BATTLEFY