Tag Archives: communication

Declarative Beats Imperative: Transforming Data In JavaScript

The product I am working on is a fairly typical web application, based on React.js and Node.js. Its main task is to fetch data from different REST-ish services, combine them, and present them in an attractive manner to users. This data extraction and transformation – keeping only the items and properties we care about and structuring them in a way well aligned with the needs of the UI – is thus crucial. I would like to share our journey from an imperative implementation of this process to a much more reader-friendly declarative one.

For example, here is some JSON data we get back from a REST service:

[{
    productId: "42",
    type: "TEAPOT",
    subProducts: [{
        productNumber: "ch132",
        name: "Kyusu Teapot",
        dealerDetails: [
          { dealerGroup: "webshop", rank: 1 }
        ]}]}];

And here is what we would like to transform it into:

{
  "42": {
    "productId": "42",
    "variations": {
      "ch132": {
        "productNumber": "ch132",
        "name": "Kyusu Teapot",
      }
    },
    "selectedSubProductId": "ch132"
  }}

My first implementation was functional, using the wonderful functional library lodash, but rather imperative. We had a series of functions that transformed some vague JavaScript object / JSON into something else. It looked something like this:
Continue reading

Intention Hidden In Implementation And Misty Edge of Validity

The code is the documentation” – except that from poorly written code you cannot tell what is an intrinsic part of the solution and what is an accidental implementation detail. And a piece of code can rarely handle any possible data – yet, without a good documentation or precondition checks, you can’t even guess at what are valid or unexpected inputs. Today we will explore a piece of JavaScript code that both hides the intention in the implementation (the “why” is not clear from the “what” the code does) and operates correctly only under particular but unstated conditions.

Continue reading