WTF code, defects, and the principle of least astonishment

We have recently introduced two defects, while trying to improve old, obscure code. Of course we are to blame for not being more paranoid and not researching more why the code was there. But if the code was clear to start with, if it followed the least astonishment principle, the errors wouldn’t have happened. In both cases the original code provoked the “WTF?!” reaction in the reader.

Continue reading

Link: DRY vs Write Explicit Tests

DRY vs WET | Arlo Being Bloody StupidWrite Explicit Tests – Following WET just asks “What is each test attempting to say? How could we say that most clearly?” An awesome example on re-writing a test into a much, much better one. It also demonstrates well that writing a good test is an iterative and challenging task – but the result is absolutely worth the effort.

Simple or Complex? Familiar Imperative Code Or Makes-Me-Think Declarative One?

We have had a heated discussion today about the two alternatives of JavaScript code that filters out elements with a different hardwareType (if supplied):


// Using http://lodash.com/ as `_`
// 1. IMPERATIVE
_(bundles).filter(function includeOnlyHandsets(bundle) {
if (!filter.hardwareType) return true;
return (bundle.product.type === filter.hardwareType);
})
// 2. DECLARATIVE
_(bundles).filter(filter.hardwareType ?
{bundle: {product: {type: filter.hardwareType}}} : null)

view raw

filter.js

hosted with ❤ by GitHub

The imperative solution (1) is familiar to all of us and thus easy to grasp. However the declarative solution (2) is not familiar, we have to think about what it does, we need to know that .filter({bundle: {product: {type: filter.hardwareType}}}) keeps only bundles that have the given product.type and that .filter(null) does keep all. Thus (1) is easy to understand, (2) isn’t.

Continue reading

Link: Refactoring to an Adaptive Model – Martin Fowler

Martin Fowler’s Refactoring to an Adaptive Model, 11/2015 – replacing imperative logic with a declarative one, with rules encoded in JSON so that they can easily be shared across platforms and updated without re-installation. A few other nice refactoring points too.

Most of our software logic is written in our programming languages, these give us the best environment to write and evolve such logic. But there are circumstances when it’s useful to move that logic into a data structure that our imperative code can interpret – what I refer to as an adaptive model. Here I’ll show some product selection logic in JavaScript and show how it can be refactored to a simple production rule system encoded in JSON. This JSON data allows us to share this selection logic between devices using different programming languages and to update this logic without updating the code on these devices.

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

Let the API Do the Hard Work: Promises in JavaScript with Q

Today’s lesson: Delegate the hard work orthogonal to your business logic – concurrency, asynchronicity, state maintenance during iteration etc. – to your language and API if you can. They are more likely to get it right and your code will be more focused on what you are actually trying to do. You should feel an unpleasant tingling when you have do these manually. We will look at JavaScript code that uses asynchronous calls to get data in a too manual (and incorrect) way and improve it to delegate the necessary synchronisation to the promises library Q that it already uses.

Continue reading

Link

Link: Insane if condition in GCC

A highly complex if statement that is/was reportedly involved in compiling lot of SW running around. The function “Reload does everything, and probably no one exactly knows how much that is.“:

Continue reading

Link: The madness of layered architecture

Johannes Brodwall: The madness of layered architecture – a nice critique of over-designed “enterprise” apps, why that is a problem (SRP, cost of code, unclear where to do a change, ….), why it is different from the successful layered network stack of Ethernet/IP/TCP/… (because in an app, all layers are on the same level of abstraction); bottom line: do not add a layer unless you have a really good reason (hint: the advice of a consultant/speaker does not count as one)

Link: Unconditional Programming

Michael Feathers’ (of Working Effectively With Legacy fame) post Unconditional Programming is well forth reading. I take the liberty of stealing parts of it:

Over and over again, I find that better code has fewer if-statements, fewer switches, and fewer loops. Often this happens because developers are using languages with better abstractions. [..] The problem with control structures is that they often make it easy to modify code in bad ways.

Includes a nice example of replacing if-else with much more readable and safer code:

A while ago, I was working on some Ruby code and I needed to write a ‘take’ function to take elements from the beginning of an array.  Ruby already has a take function on Enumerable, but I needed to special behavior.  If the number of elements I needed was larger than the number of elements in the array, I needed to pad the remaining space in the resulting array with zeros.

The naive if-based implementation:

  def padded_take ary, n
    if n <= ary.length
      ary.take(n)
    else
      ary + [0] * (n - ary.length)
    end
  end

The final one, which seems much nicer and easier to understand to me:

  def padded_take ary, n
    pad(ary, n).take(n)
  end

  def pad ary, n
    pad_length = [0, n - ary.length].max
    ary + [0] * pad_length
  end

Read the original post for a full discussion and explanation of why.

Surfacing Hidden Design: Seeking A Better Alternative To Interrelated Mutable Fields

What is better, a bunch of mutable boolean fields and methods operating on them, or an explicit expression of the individual states and transitions between them? Lets study an example from a simulation of the progression of a multi-stage infection.

1. Design hidden in primitive mutable fields and methods

The following class, with a number of interrelated mutable (public) fields, which I should have completed with methods for transitions between their states, made me really uneasy (a var is a mutable field, val is immutable):


class Person (val id: Int) {
var infected = false
var sick = false
var immune = false
var dead = false
// to complete with simulation logic
// [infection progression]
}

The fields keep the state of the progress of an infection. They depend on each other – f.ex. when sick, the person must also be infected, while when dead, she must not be immune.

The progression of the infection is: healthy -> infected and infectious with the chance of 40% (but not visibly sick yet) -> on day 6 visibly sick -> on day 14 dies with the chance of 25% -> if not dead, becomes immune on day 16 – not visibly sick but still infectious -> healthy on day 18.

The problem I have with keeping the state in a bunch of fields is that there is no explicit expression of these rules and that it opens for defects such as setting sick to true while forgetting to set also infected. It is also hard to understand. You could learn the rules by studying the methods that alter the fields but it requires a lot of effort, it isn’t easy to distinguish between an incidental implementation detail and intentional design and this code does not prevent mistakes like the one described.

Continue reading