Today I Learned - Rocky Kev

TIL newbie-friendly code code organization

POSTED ON:

TAGS:

I really like these rules of thumbs a lot, from Building a newbie-friendly codebase

These are more about organizing your codebase.

The key things I like:

Convention everything

The left is vague. Where the right has clear context of what each file is about.

I like this one too:

// You can totally do this
buttonToChangeColor.addEventListener(button => {
if (button.color == Color.RED) {
button.color = Color.BLUE
} else {
button.color = Color.RED
}
})

// Something more 'contextual'
buttonToChangeColor.addEventListener(button => updateColor(button))

It’ll be much easier to focus on what the click listener is doing rather than where or how it’s doing it, which is unequivocally more important.

Information flows in a one-way street

Have a single source of truth and unidirectional data flows. It’s easier to understand where data is created, propagated to, accessed and which actions can modify it.

Having multiple places creating or updating the same data makes the flow of information and cascading effects hard to understand, creating a highway for bugs that are hard to debug and fix.

Use data structures


// BEFORE
const STATE_LOADING = "state_loading"
const STATE_LOADED = "state_loaded"

const state: (...) // getting the state

switch (expr) {
case STATE_LOADING:
// ...
break;
case STATE_LOADED:
// ...
break;
default:
// ...
}

Right now, you can have a lot of surprise states and would have to create a bunch of variables for that.

A better use-case would be to use enums.

Enums are types that contain a limited number of fixed values.

// BETTER VERSION
const STATE = Object.freeze({
STATE_LOADING,
STATE_LOADED
})

Acronyms are B.A.D.

Instead of using PDP to refer to your ProductDetailsPage, use its full version. Characters are free, and it’ll be clear for everyone what you’re referring to.

It kinda depends.

I think .bg-red is pretty acceptable. Everyone agrees that it bg means background.

But I absolutely hate usrOptions. Really? You want to save a single keystroke?


Related TILs

Tagged:

TIL newbie-friendly code code organization

Adding clear conventions. One-way street data flow. Data structures. Stop it with Acronyms.

TIL newbie-friendly code code organization

Adding clear conventions. One-way street data flow. Data structures. Stop it with Acronyms.

TIL newbie-friendly code code organization

Adding clear conventions. One-way street data flow. Data structures. Stop it with Acronyms.