DEV Community

Discussion on: The Art of Refactoring: 5 tips to Write Better Code

Collapse
 
oshell profile image
oshell

The example with the switch statement sounds cool first, but is far from any real world use case. Yes, if all I do with the switch is checking a string I can move it to an object. But normally I check against boolean values, returned from several function calls. Maybe you should mention that.

In my opinion the most important thing is to have readable statements. Instead of putting multiple values into the if statement, define a new variable describing what this statement contains. You sacrifice minimal resources for much more readability. No comments needed. E.g.:

const pictureIsValidForUpload = validWidth && validExtension && validMimeType;
If (pictureIsValidForUpload) { upload();}

Collapse
 
dancalderon profile image
Daniel Calderon • Edited

I'm not sure if you need a switch statement to check a boolean in first place.

The object alternative to the switch statement could work when you have different conditions to be checked.

E.g:

let type = 0;
const objContent = {
0: 'first',
1: 'second',
2: 'test',
23: Michael''
}

content = objContent[type]

This is easier to read than a switch statement or even a regular if

if(type === 0) return "first"
else if(type === 1)...etc