Supple Design in Node.js

14th April 2019 / In Javascript Domain Driven Development

In this blog post I will be talking about ways you can apply supple design in Node.js projects.

Intention Revealing Interfaces

The idea of intention revealing interfaces is to not have to dive into the implementation of a function to know what the function does. Now we know that JavaScript doesn’t have interfaces in the sense of Object Oriented Design; but interfaces are not just that. Interfaces are ways to use code. The calling of a function is the use of an interface because we don’t care about the implementation, rather what it does.

Intention revealing interfaces makes it so the code is flows while you read it and any person can understand it. The easiest way to apply this principle is to name your functions with meaningful words. Instead of writing createPostcard(user,payload) for a function that makes a certain user collect a postcards, you can write collectPostcard(user, postcardInformation). Don’t cut out names if by shortening it makes it not easily understandable. You have to make the code as readable as possible so the client (thing that uses your code) can understand the intention behind your code.

Side Effect Free Functions

A side effect in this case is “any program state change other than expression evaluation”. By this definition we know that not all functions are side effect free. This is because there are functions that don mutations to your entities and changes the state of the system. A useful way of applying supple design is to make all of the possible functions side effect free. This is accomplished by making functions that change the state of the system, as simple as possible. Another way you can do this is by making functions that change the state of an object return another new value object with the changes applied instead of changing the given object.

The reason you want to do this is because they are easier to test and reason about. This also allows for safe combination of operations.


What do you do with the side effects that are still in your functions? Well, you want to make sure what does that function does in order to make sure your code does what you want to do. A way of making the side effects explicit is by using assertions. Assertions can be post-conditions, pre-conditions and invariants. These describe the state of an object but not the procedures, which makes it useful for the client. While I use a testing framework to do assertions, you can also use the Node.js Assert Module to do this.

Also, remember to write assertions in documentation and diagrams!

A last word, remember to refactor often! You can end up with duplicated work or very granular functions which is not useful. Always think about the design and check if it makes sense!