Skip to content
Advertisement

Cleaner Alternative to Nested If/Else

I’m mainly focused on an alternative to if/else’s in create_animal. If there is a more professional way to handle this.

In this case, it’s a classifier based on a variable number of traits needed to figure out what the animal is. Since humans are the only animals that speak English, that property is sufficient. But if they roar instead Bear and Lion need an additional property of habitat to figure it out. I know I could group those conditionals more succinctly, but that’s not what I’m trying to illustrate.

JavaScript

This will work, but for some real world complexity, I don’t like how nasty the nested if/else’s are getting and I figure there must a good way to do it with a classification map like this, but I’m not sure how to approach it.

JavaScript

Advertisement

Answer

One option that at least standardizes your function inputs is to have each animal classified by it’s language and habitat and store it in a dictionary

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement