Hi everyone, this is something I recently learned and I would like to share with everyone. It is something small but at the same time it becomes a good practice that can greatly improve our code.
Magic Strings
We can define this as using hardcoded code that contains a specific string, either to handle a state, compare a value, or store a value that we, for whatever reason, need to have hardcoded.
For example:
if(this.userStatus === 'online'){
//any
}
The problem
If you need to check this status in multiple parts of your code by any reason, someone can easily make a typo error and write something like:
if(this.userStatus === 'onlien'){
//any
}
and the code won't work as expected.
Solution
The most obvious solutions should be to create a constant and use this constant when necessary, but what if we have a lot of constants related to that specific functionality? We should create an object with all possible words.... A Dictionary.
export const USER_STATUS = {
online: 'online',
offline: 'offline',
connecting: 'connecting'
}
export default class Example {
checkStatus() {
if(this.userStatus === USER_STATUS.online){
//any
}
}
}
Mutability
We still have a problem here, even if it's a constant, we could edit the content of our object and overwrite the value by mistake.
USER_STATUS.online = 'hi'
To avoid this we can improve the code making it immutable.
Immutability
Freezing an object prevents extensions and makes existing properties non-writable and non-configurable.
export const USER_STATUS = Object.freeze({
online: "online",
offline: "offline",
connecting: "connecting"
});
Point of improvement
At this point our dictionary is ready, however there are cases where we use these values only internally in our application, i.e. we don't need any specific text, it can be a number or anything.
In these cases we could use symbol and avoid the fatigue of adding different strings or numbers for each part of our dictionary. Symbol will always make sure to assign a different value.
export const USER_STATUS = Object.freeze({
online: Symbol(),
offline: Symbol(),
connecting: Symbol()
});
And that's all, thanks for reading and I hope this helps you organize your code better.
You can also see an small example here:
https://codesandbox.io/s/runtime-dust-zbkfth
Bye bye!
Top comments (1)
Hey there! I just read your post and I really liked it. However, I noticed that your code snippets seem a bit off. I thought I'd share a guide that might help you format them properly. Let me know if you have any questions or need further assistance. Keep up the great work!