TIL writing a clean function
POSTED ON:
TAGS: testing functional-programming
I see a frequent junior mistake is to just start writing functions. Then writing more and more until suddenly, this function becomes too bloated.
And as a functional programmer, I like my functions as short/percise as possible.
When I write a function, I follow this process:
- What is the goal?
- What is it supposed to return?
- What type of params does it take?
- What is the logic from param -> return?
I saw a quote that really encapsulated my process into a brief sentence.
Write an assert at the beginning of the function. Then, write down all the conditions that must be met.
"All the conditions that must be met" is such a beautiful statement.
The assert
part might be a bit too hard for a junior to start thinking about. But they can still do things like:
// this function will:
// 1. check to see if it's a number
// 2. If it's even, return a agreement
// 3. If it's odd, return a reject
function isNumberEven(num) {
if (!typeof num === 'number') return "Not a number";
// ...
}
After writing that assert, the code writes itself.
Via this post: 16 Things I Always Say to My Juniors for Bug-Free Programming
Related TILs
Tagged: testing