Key principles to writing better Javascript

mtendekuyokwa19

Mtende Otis II

Posted on June 6, 2024

Key principles to writing better Javascript

Since the day I started writing code, I believe I was always writing bad code. I didn’t notice it was bad until I started working on a mini-project that was not really mini. As the project grew , I found myself debugging my project just to slot in the features and updates.

Accepting this was like eating a boiled sweet potato without a drink(a Malawian equivalent proverb to hard pill to swallow). But I had to accept this_ uncomfortability_. I first started by hunting for tips and experiences mostly on Hacker news and Reddit.

The collection of blog post mostly lead to the SOLID principle

We’re SOLID? yes
SOLID is and abbreviation that screams Single responsibility, Open-closed,Liskov substitution, Interface segregation,Dependency Inversion.

It is 100% okay if this sounds like something off a philosophical book.Out of the five, I really wanna tether around Single responsibility.

SINGLE RESPONSIBILITY
This principle drives my daily function architecture. A function should only do one thing. If your function is made to add two numbers that’s all it should do, nothing extra.

You’ll sometimes find yourself questioning whether the task my function is one. Let me support this previous statement with a snippet.

function multiply(a,b){

return a*b;
}
Enter fullscreen mode Exit fullscreen mode

This function above clearly does one thing and thats (drum roll) multiplication. Hence this qualifies as single responsibility.

Evaluate this next snippet

function multiply(a,b,answer){
answer=a*b;
return answer;
}
Enter fullscreen mode Exit fullscreen mode

The second function also qualifies as single responsibility. But the second function is bad code.
The core reason why the second function is bad is that it involves manipulation of outside values(answer). The terminology for this is mutation.

Even though mutation has alot of advantages its downside is that if alot of functions are mutating it becomes hard to track where bugs are coming from. FYI, this reason is also why global variables are discouraged. Some languages even use access modifiers to prevent this.

Single responsibility should always be considered when you are writing your functions because it is easier to track bugs and makes easier addition of features when scaling.

💖 💪 🙅 🚩
mtendekuyokwa19
Mtende Otis II

Posted on June 6, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related