Recently, I had a take home assignment for a front end role, and I had to make a sort of Dashboard. I thought I did everything right, but I was rejected, partly on my carelessness, and also due to my code. I was using too many if/else statements everywhere! And I didn't know any better. But now I do, and I'm here to share that with you.
Most of us use if/else and switch statements whenever there is some conditional logic to handle. Although it might be a good idea to do that for one or two conditions here and there, using multiple if else statements chained together or big switch statements will make your code look very ugly, less readable and error prone.
function whoIsThis(character) {
if (character.toLowerCase() === 'naruto') {
return `Hokage`
} else if (character.toLowerCase() === 'sasuke') {
return `Konoha's Strongest Ninja`
} else if (character.toLowerCase() === 'isshiki') {
return `Otsutsuki being`
} else if (character.toLowerCase() === 'boruto') {
return `Naruto and Hinata's son`
}
}
whoIsThis('')
You see that we are repeating ourselves many times by writing multiple console.logs and if statements.
But there's an Object-Oriented way of doing this, and that is by using Objects.
Instead of writing if else blocks we just define an object which has the values we use in comparisons as keys, and the values we return as values of the objects, like so:
function whoIsThis(character) {
const listOfCharacters = {
'naruto': `Hokage`,
'sasuke': `Konoha's Strongest Ninja`,
'isshiki': `Otsutsuki being`,
'boruto': `Naruto and Hinata's son`
}
return listOfCharacters[character] ?? `Please provide a valid character name`
}
By using objects, we were able to make a sort of dictionary to look up to, and not use multiple if-else statements.
We can also make this better by using the Map object instead of using an object. Maps are different from normal objects:
- They remember the original order of insertion
- Unlike objects, we can use any type of data as key/value, not just strings, numbers and symbols.
function whoIsThis(character){
const mapOfCharacters = new Map([
['naruto', `Hokage`],
['sasuke', `Konoha's Strongest Ninja`],
['isshiki', `Otsutsuki being`],
['boruto', `Naruto and Hinata's son`]
])
return mapOfCharacters.get(character) ?? `Please provide a valid character name`
}
Thanks for reading this short article, if you liked it, you can support my work at https://www.buymeacoffee.com/rishavjadon
Latest comments (65)
Can you share why would this be more readable/maintainable? I'm worried about you saying that this is "more readable and maintainable" without giving quality arguments about why that's true, that may let people believe that this is a must always.
I just went into a discussion about this topic, and some people argue that:
Is better than a simple if like:
This is an abuse/overuse of a language feature or structure which involves more concepts and more time on your brain in order to understand what is happening when you read it.
I also believe that this enlarge possible problems in devs minds like "Primitive types obsession" and "Declarative Dilussion", check:
WDYT?
else if
andMap
both work for your case, but they're not interchangeable in general - one is a control structure and the other one is a data structure.else if
is not inherently bad, it can be the most precise solution for some specific problems.Interesting.. no one mentions the Minification proces, and how that optimizes your code.
Thank you
good,jobs. This idea is very good. Dictionary way, okay. The usage scenario in this way is to switch between different branches according to the incoming value. At that time, if you donβt pass in a value, you need to switch to a different branch, how to do ?
neat approach to improving readability (and apparently also efficiency), I like!
small suggestion from my point of view, you called the valid characters object listOfCharacters but I would rather go with validCharacters or sth similiar. Since the variable is technically not a list
Sorry, but I don't agree at least with your example. Why not a switch case?
That would also be almost like if else.
Almost how? Did you meseare the performance? Can you be more specific?
Thanks for the tips today at work I remember Iβve see your article and thatβs save my code of a bunch of if/else. ;)
I'm glad it helped, thank u :)
Stop telling me what to do
Stop telling me to stop telling you what to do.
πππππππ This is a good one ! Nice article mate.
I suggest watching videos or looking at the blog of Uncle Bob, the Clean Coder. He also supports this view.
He suggests another solution - polymorphism. Not needed for a simple case of matching string results but if you had more complex logic it would be worth making classes which all implement the same method. And then you pass in a class instance to a function and it calls the method of the class - no need for if statement or keylookup.
It's possible too outside of classes - but probably requires type system from TypeScript and overloading function so you call a variation of a function depending what type you pass in.
Some comments may only be visible to logged-in visitors. Sign in to view all comments. Some comments have been hidden by the post's author - find out more