DEV Community

Discussion on: 5 easy wins to refactor even the ugliest code

Collapse
 
gtanyware profile image
Graham Trott • Edited

If switch is implemented by the compiler as a look-up table it might offer somewhat better performance, especially as the number of options grows. Actually, I often prefer switch to chained ifs as to me it's more aesthetic; it's saying clearly "Here's a set of options to choose from". You can still implement return instead of break in any of the cases. But I guess a lot of things are down to personal preference.

Whenever I see multiple choices of this kind I like to use tables, so I'd try something like this, which also permits easy initialization from JSON (warning: untested code):


const images = {
   "hiphop": "https://unsplash.com/photos/Qcl98B8Bk3I",
   "jazz": "https://unsplash.com/photos/dBWvUqBoOU8",
   "rap": "https://unsplash.com/photos/auq_QbyIA34",
   "country": "https://unsplash.com/photos/RnFgs90NEHY"
};

const url = images[track.getGenre()];
return {
   dimension: 'small',
   url: url ? url : 'https://unsplash.com/photos/PDX_a_82obo'
};
Enter fullscreen mode Exit fullscreen mode
Collapse
 
mlevkov profile image
Mikhail Levkovsky

Great point! This was just to illustrate an example but yours illustrates it even better :)
Thanks for sharing it!
To be honest, I would prefer to have a designated factory to create these things so as not to mix behavioural and creational logic in one class.

Collapse
 
gtanyware profile image
Graham Trott

I'd agree with you there Mikhail. It makes the overall program so much more concise and readable.

One of the joys (and frustrations) of JavaScript is there are so many different ways of doing the same thing. As I typed the words "look-up table" I suddenly recognized a pattern, where all the text could be extracted into constant data separate from the behavior. Sometimes you approach these things sideways and the pattern leaps out at you from nowhere.