Functional Thinking
This weekend, I was reading a recently released book called Grokking Simplicity, the purpose of the book is to teach functional programming without using the technical jargon. (If you know FP, this book may not be for you? It is for developers asking the question what is FP?)
I am very impressed with the book, from a beginner perspective I think it will be relatable to students who are just getting started. If practiced, it can create habits to form solid architecture discipline when building applications using any paradigm. The art of breaking large problems in to small pieces takes lots of practice and lots of iteration.
To start the book creates three easy to understand definitions of classifying your code:
- Actions
- Calculations
- Data
Actions
Any function that the execution depends on when it is called or how many times it is called.
Calculations
Any function that takes zero to many input arguments and returns the same output for the same arguments every time it is executed. Some may call these pure functions.
Data
Facts created from events, these facts are concrete data for a given state.
Example
So how would go about breaking down existing code using these definitions? Lets take a couple examples:
// data
const PersonObject = (name, age) => ({
name: name,
age: age
})
// calculation
const assoc = (key, value, obj) => ({ ...obj, [key]: value})
// action
const log = (data) => console.log('data', data)
The hidden action
These examples should clearly show, what is an action, calculation and data, but some functions can hide the fact they are actions, if I call a function within my function that is an action, then my function becomes an action too. Actions can spread like a virus throughout our code base. Actions are where the most gnarly bugs live. While actions are very important for your application, by pushing the actions to the boundaries of your application, you are able to contain virus and keep the bugs easy to find and trap.
// hidden action
const doSomething() {
...
log(data)
...
}
Summary
By applying these simple classifications to your code you can get cleaner code without having to use any fancy functional language or utility library. This is called Functional Thinking, there is more, but take some time and give some thought to this style of classifying your code and see how many actions, calculations, and data functions one of your use cases contain. Try refactoring your actions in to more calculations. You will find your code becomes easier to test, maintain, and will feel reliable.
For more information on Functional Thinking
Check out the new book by Eric Normand - https://www.manning.com/books/grokking-simplicity