samedi 3 septembre 2022

How to restructure nested if else statement

Say you have the following table for a monster object:

Gender Age Type Result
Male Young Fire 1
Male Old Ice 2
Male Old Wood 6
Female Young Fire 4
Female Old Ice 5
Female Old Wood 8
Other Young Fire 7
Other Old Ice 10
Other Old Wood 20

If I were to have a monster and input it to get a result; how would I get the result of the monster object without making a long nested if-else statement?

if(monster.Gender == Male && monster.Age == Old)
    if(monster.Type == Ice)
        return 2
    if(monster.Type == Wood)
        return 6
if(monster.Gender == Male && monster.Age == Young)
etc...

I can't seem to wrap my head around making it extensable and such: say I want to add a column in the future or want to validate something before another thing.

Are there any simple design patterns or the like that I can implement to simplify it and make it extensible?

Aucun commentaire:

Enregistrer un commentaire