DEV Community

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

Collapse
 
aminmansuri profile image
hidden_dude

I think the obvious way to get rid of switch statements and long if/else clauses is with OO:

Instead of asking what "type" something is, use an objet that has all the attributes about that type in it.

so instead of :

getPokemon(type)

You'd write:

pokemon = Pokemon.fromString(typeStr)

name = pokemon.getName()

The obvious advantage is that instead of having a bunch of switch statements in your code, or a bunch of if/elses, or a bunch of tables that trigger on type, you have a single object that encapsulates the entire description of the pokemon, including name, preferences, color, size, etc.. You may have a table (or switch or if/else) to create that object from a string that indicates the "type". Or you could just use the specific class name everywhere (or prototypes if you prefer to do it that way).

That's fairly basic OO, I'm kind of surprised nobody mentioned this.