Today I Learned - Rocky Kev

TIL writing a clean function

POSTED ON:

TAGS:

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:

  1. What is the goal?
  2. What is it supposed to return?
  3. What type of params does it take?
  4. 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:

TIL Scoping with Cypress

So you wanted to find a specific element called `heading`. But you have a BUNCH of elements called `heading`. By using `within()` helper, you can force it to only look inside `main` elements.

TIL MSW for mocking

MSW is a API mocking tool. Mock by intercepting requests on the network level. Seamlessly reuse the same mock definition for testing, development, and debugging.

TIL writing a clean function

Write an assert at the beginning of the function. Then, write down all the conditions that must be met.